Thread 1:
putQ
setFlag
Thread 2:
while (1) {
waitFlag
processQ
clearFlag
}
This is an interview question. I am not sure whether there is a while loop for Thread 1.
But the answer is like when Thread 2 re-enter the while loop, two threads go into deadlock.
Can anyone tell me what’s condition for deadlock? Thanks.
I think the OP’s comments are correct:
@Gray: This is most likely NOT a dead-lock, but a race condition. Yet the application is stuck not processing the queue, so it’s a lock.
@Wug: It is probably the “trivial case” where while
thread 1has put in the queue and updated the flag,thread 2will never notice. See course of action below.Potential lock situation:
ProcessQElement 0 (processing a former element)PutQElement 1SetFlagClearFlagwaitFlagElement 1 might never be processed.
EDIT:
Of course, the next question would be:
how do you fix that?The answer would be with a
Conditional Variable(seepthread_cond_initand others for details):Thread 1:
Thread 2: