How to pause an NSThread until notified?

后端 未结 1 813
名媛妹妹
名媛妹妹 2020-12-03 03:50

I have a worker thread that I want to do one bit of its task, then pause & wait for the \"ok, continue\" command from another thread, then pause & wait, etc.

相关标签:
1条回答
  • 2020-12-03 04:29

    Look into NSCondition and the Conditions section in the Threading guide. The code will look something like:

    NSCondition* condition; // initialize and release this is your app requires.
    
    //Worker thread:
    while([NSThread currentThread] isCancelled] == NO)
    {
        [condition lock];
        while(partySuppliesAvailable == NO)
        {
            [condition wait];
        }
    
        // party!
    
        partySuppliesAvailable = NO;
        [condition unlock];
    }
    
    //Main thread:
    [condition lock];
    // Get party supplies
    partySuppliesAvailable = YES;
    [condition signal];
    [condition unlock];
    
    0 讨论(0)
提交回复
热议问题