Re: PR_WaitCondVar
Wan-Teh Chang <[email protected]>
| Newsgroups | gmane.comp.mozilla.devel.nspr |
|---|---|
| Message-ID | <[email protected]> |
[email protected] wrote: > > I have two doubts. Consider the code below. > Please read that comments in the code. > > void start1 (void * arg) > { > int ret = 1; > > while (1) > { > printf("\nHello this is thread: 1\n"); > > PR_Lock(mylock); > > PRIntervalTime start = PR_IntervalNow(); > > PR_WaitCondVar(mycond, INTERVAL); /*Let INTERVAL is 1000 */ > /* Suppose the above function returned because of recieving > signal afrer 999 milli sec*/ > > PRIntervalTime elapsed = PR_IntervalNow() - start; > /* The above function somehow took 1 milli sec to return*/ > /* So now 'elapsed' is 1000*/ > > if (elapsed >= INTERVAL) > { > /* Then will it enter here? And report 'timed out' > instead of 'signaled' ?*/ > printf("\nTimed Out\n"); > } > else > { > printf("\nSignaled\n"); > } > > PR_Unlock(mylock); > } > } The unit of PRIntervalTime is platform dependent. We call it a "tick". A tick is not one millisecond on all platforms. So to specify a 1000 millisecond timeout in PRIntervalTime, you need to call PR_MillisecondsToInterval(1000). As your comments described, you will enter the "elapsed >= INTERVAL" case and report "timed out". Your code has a bug -- you must always call PR_WaitCondVar in a while loop: while (!condition_you_are_waiting_for) { PR_WaitCondVar(...); } You cannot assume that when you return from PR_WaitCondVar, the condition is true. There are three reasons why the condition may not be true: 1. PR_WaitCondVar may return without being signaled. This is called a spurious wakeup. 2. If there are other threads waiting on the same condition variable, some other thread may wake up before you do, modify the shared data, and make the condition false again. So when you wake up, the condition may be false. 3. PR_WaitCondVar may return because of a timeout. Note that these issues also apply to pthreads' condition variables and Java objects' Wait and Notify/NotifyAll methods, so you also need to wait in a while loop in pthreads and Java. > Second doubt is - say the conditional variable is signaled just at > INTERVAL. > Then what will happen? If that's the case, PR_WaitCondVar will return, and "elapsed >= INTERVAL" will be true. Only you can decide how you should handle this case. The wait timed out, but the condition you're waiting for has become true. Depending on the application, you should report a timeout (because you waited too long) or you can go ahead and process the data. Wan-Teh