On Sep 29, 11:38=A0am, calvin <chima1...@[EMAIL PROTECTED]
> wrote:
> Thanks, DS. So POSIX does has such a bug?
No, your code does.
> What do you mean "This bug usually occurs because a thread called
> pthread_cond_wait when it should not have." I think whether a thread
> should call pthread_cond_wait is the merely logic of my problem,
> right?
Right. I'm suggesting that your code has a bug -- it calls
pthread_cond_wait when it should not have. Suppose you go to a place
that has a "take a number" system. If you just blindly take a number
and start waiting, you'll wake forever if they're not using the take a
number system. You must first check to be sure you need to wait before
you start waiting. If the thing you're waiting for has already
happened or will not happen, you must not wait for it.
It's a very common logic error. You must:
1) Take the mutex.
2) Check the predicate. If true, jump to step 4.
3) If the predicate is false, block on the condition variable
(automatically releasing the mutex) and jump to step 2.
4) Act on the predicate.
5) Release the mutex.
Note that the decision whether or not to call pthread_mutex_wait is
based on the predicate and is made while the mutex is held. The mutex
is only released by the call to pthread_cond_wait.
The "pthread_cond_wait" call is *NOT* a conditional wait. It is an
unconditional wait. Do not call it unless you are sure you need to
wait.
Suppose you share a car with your sister. You must make sure your
sister has the car before you wait for her to come home. If your first
step is "wait for my sister to come home with the car", you'll be
waiting a long time if she's in bed and the car is in the driveway.
Then when you find her in bed later and the car in the driveway you
might think, "wow, my sister didn't tell me when she got home, it's
her fault". But it's your fault -- you didn't check to see if she was
already home before you waited for her.
DS


|