15

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.

The use case is: the controlling object is a view that I want to display information about what's going on inside the worker-thread, and allow me to "single-step" through the worker as it does it's thing.

The rather ugly and heavy-handed thing that I have in my worker is this:

NSLog(@"paused");
paused = YES;

while (paused)
{
    [NSThread sleepForTimeInterval:0.25];
}
NSLog(@".. continuing");

...But I can't help but think that there must be a nicer way, perhaps involving NSLocks, or some such.

Comments, hints suggestions?

Thanks!

Olie
  • 24,597
  • 18
  • 99
  • 131

1 Answers1

26

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];
nall
  • 15,899
  • 4
  • 61
  • 65
  • 2
    Also note, for future spelunkers: `NSConditionLock`, where you do something like `[condition lockWhenCondition: suppliesAvailable]; mySupplies = [supplyQueue contents]; [supplyQueue removeAllSupplies]; [condition unlockWithCondition: noSuppliesAvailable]; // spend mySupplies as desired` is a very useful pattern. In my case, rather than partySupplies, I have it as data that needs processing. QED. – Olie May 27 '14 at 20:18
  • +1 for getting the party started. :D Great use of partySuppliesAvailable and // party! – Alexandru Jun 16 '14 at 00:45