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?