Friday, April 19, 2013

NSConditionLock example objc


Overview

The NSConditionLock class defines objects whose locks can be associated with specific, user-defined conditions. Using an NSConditionLock object, you can ensure that a thread can acquire a lock only if a certain condition is met. Once it has acquired the lock and executed the critical section of code, the thread can relinquish the lock and set the associated condition to something new. The conditions themselves are arbitrary: you define them as needed for your application.
Example of NSConditionLock

#import <Foundation/Foundation.h>
#define NOT_DONE 0
#define DONE 1

// this will need to be on some class that is calling the NSThread object
-(void) someFunc:(id) arg {
NSConditionLock* myLock = arg;
[myLock lock];
//do stuff that we need to know about in main
[myLock unlockWithCondition:DONE];
}


int main() {

NSConditionLock* finishedLock = [[NSConditionLock alloc]
initWithCondition: NOT_DONE];

NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(someFunc:) object:finishedLock];

[myThread start];

[finishedLock lockWhenCondition:DONE];

// now we can do whatever we need to do with the results from
// the thread we spawned

}
Example of NSConditionLock