I'm using NSCondition class in this sence:
- (void) method1
{
[[cocoaCondition lock] lock];
while (!someCheckIsTrue) {
[cocoaCondition wait];
}
// Do something.
[cocoaCondition unlock];
}
- (void) method2
{
[cocoaCondition lock];
// Do something.
someCheckIsTrue = YES;
[cocoaCondition signal];
[cocoaCondition unlock];
}
I have two threads, thread1 runs the method1 and thread2 runs the method2. I hope that when [cocoaCondition wait]
is called, the thread1 will be blocked. Then when the thread2 calls [cocoaCondition signal]
, the thread1 will resume running. I've test the code and it works just as I hope.
But, as you see, when the code running:
step 1, thread1 calls: [cocoaCondition lock]
(Apple doc says: Attempts to acquire a lock, blocking a thread’s execution until the lock can be acquired)
step 2, thread1 calls: [cocoaCondition wait]
step 3, thread2 calls: [cocoaCondition lock]
(Following the apple's doc, the thread2 should be blocked)
step 4, thread2 calls: [cocoaCondition signal]
(So, the thread2 should be blocked and can't call this method until the [cocoaConditon unlock]
is called)
I think my code is deadlocked, but why not?
So I guess the cocoaCondition is unlocked when the thread1 calls [cocoaCondition wait]
on the step 2, is it?
The document says: "When a thread waits on a condition, the condition object unlocks its lock and blocks the thread. When the condition is signaled, the system wakes up the thread. The condition object then reacquires its lock before returning from the wait or waitUntilDate: method. Thus, from the point of view of the thread, it is as if it always held the lock."
Your guess was right.
来源:https://stackoverflow.com/questions/8611994/how-does-the-nscondition-work