4

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?

schumyxp
  • 112
  • 1
  • 9
  • 1
    Why do you need the while loop? Can't you just call wait and then once signal is called wait will exit? – jjxtra Dec 12 '12 at 19:58
  • 1
    @jjxtra from Apple's NSCondition doc: "A boolean predicate is an important part of the semantics of using conditions because of the way signaling works. Signaling a condition does not guarantee that the condition itself is true. There are timing issues involved in signaling that may cause false signals to appear." – Gobe Jun 03 '16 at 18:22

1 Answers1

8

NSCondition Class Reference

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.

Besi
  • 22,579
  • 24
  • 131
  • 223
MasterBeta
  • 606
  • 6
  • 15