← Back to team overview

linuxdcpp-team team mailing list archive

[Bug 617021] Re: Semaphore potentially may underflow and become negative

 

** Branch linked: lp:~gpr/dcplusplus/sync

-- 
Semaphore potentially may underflow and become negative
https://bugs.launchpad.net/bugs/617021
You received this bug notification because you are a member of LinuxDC++
Team, which is subscribed to LinuxDC++.

Status in DC++: New
Status in Linux DC++: Confirmed

Bug description:
As noted in POSIX about pthread_cond_wait, spurious wakeup may occur and predicate should be rechecked after wakeup.
So the patch.

diff --git a/client/Semaphore.h b/client/Semaphore.h
index f89148d..b0c59e5 100644
--- a/client/Semaphore.h
+++ b/client/Semaphore.h
@@ -61,7 +61,7 @@ public:

        bool wait() throw() {
                Lock l(cs);
-               if(count == 0) {
+               while (count == 0) {
                        pthread_cond_wait(&cond, &cs.getMutex());
                }
                count--;
@@ -76,7 +76,10 @@ public:
                        millis+=timev.tv_usec/1000;
                        t.tv_sec = timev.tv_sec + (millis/1000);
                        t.tv_nsec = (millis%1000)*1000*1000;
-                       int ret = pthread_cond_timedwait(&cond, &cs.getMutex(), &t);
+                       int ret;
+                       do {
+                               ret = pthread_cond_timedwait(&cond, &cs.getMutex(), &t);
+                       } while (ret==0 && count==0);
                        if(ret != 0) {
                                return false;
                        }





References