I am using BFTasks to perform some SpriteKit drawing in the background, but I'm not sure I'm using them correctly, as the drawing is locking up the main thread.
Each object is made up of several SKSpriteNodes, that are flattened before rendering. I'd like each one to render as soon as it's been flattened, i.e. when I call [self addChild:miniNode]; But it waits until all have been created, (locking the main thread) and then they appear all at once.
I've simplified my code below to show the chain of tasks:
- (void)drawLocalRelationships
{
[ParseQuery getLocalRelationships:_player.relationships block:^(NSArray *objects, NSError *error) {
[[[self drawRelationships:objects forMini:_player]
continueWithBlock:^id(BFTask *task) {
//this continues once they've all been drawn and rendered
return nil;
}];
}];
}
- (BFTask *)drawRelationships:(NSArray *)relationships forMini:(Mini *)mini
{
return [_miniRows drawSeriesRelationships:relationships forMini:mini];
}
The MiniRows class:
- (BFTask *)drawSeriesRelationships:(NSArray *)relationships forMini:(Mini *)mini
{
BFTask *task = [BFTask taskWithResult:nil];
for (Relationship *relationship in relationships) {
task = [task continueWithBlock:^id(BFTask *task) {
return [self drawRelationship:relationship mini:mini];
}];
}
return task;
}
- (BFTask *)drawRelationship:(Relationship *)relationship mini:(Mini *)mini
{
//code to determine 'row'
return [row addMiniTask:otherMini withRelationship:relationship];
}
The Row class:
- (BFTask *)addMiniTask:(Mini*)mini withRelationship:(Relationship *)relationship
{
//drawing code
MiniNode *miniNode = [self nodeForMini:mini size:size position:position scale:scale];
[self addChild:miniNode]; //doesn't actually render here
return [BFTask taskWithResult:nil];
}
I've tried running the addMiniTask method on a background thread, but it doesn't seem to make a difference. I wonder if I'm misunderstanding the concept of BFTasks - I figured they're automatically run on a background thread, but perhaps not?
BFTasks are NOT run on a background thread by default !
If you do:
BFTask * immediateTask = [BFTask taskWithResult: #"1"];
immediateTask completes, i.e. the completed property is YES, immediately in the current thread.
Also, if you do:
[task continueWithBlock:^id(BFTask *task) {
// some long running operation
return nil;
}];
Once task completes, the block is executed in the default executor, which executes blocks immediately in the current thread unless the call stack is too deep in which case it is offloaded to a background dispatch queue.
The current thread being the one where continueWithBlock is called.
So unless you're calling the previous code in a background thread, the long running operation will block the current thread.
However, you can offload a block to a different thread or queue using an explicit executor:
BFTask * task = [BFTask taskFromExecutor:executor withBlock:^id {
id result = ...; // long computation
return result;
}];
Choosing the right executor is critical:
executor = [BFExecutor defaultExecutor] the task's block is run on the current thread (the one where the task creation is performed) or offloaded to a background queue if the call stack is too deep. So it's hard to predict what will happen;
executor = [BFExecutor immediateExecutor] the task's block is run on the same thread as the previous task (see chaining below). But if the previous task was run by the default executor you don't really know which thread it is;
executor = [BFExecutor mainThreadExecutor] the task's block is run on the main thread. This is the one to use to update your UI after a long running operation.
executor = [BFExecutor executorWithDispatchQueue:gcd_queue] the task's block is run in the supplied gcd queue. Create one with a background queue to execute long running operations. The type of queue (serial or concurrent) will depend on the tasks to execute and their dependencies.
Depending on executor you will get different behaviour.
The advantage of BFTasks is that you can chain and synchronise tasks running in different threads. For example, to update the UI in the main thread after long running background operation, you would do:
// From the UI thread
BFTask * backgroundTask = [BFTask taskFromExecutor:backgroundExecutor withBlock:^id {
// do your long running operation here
id result = ...; // long computation here
return result;
}];
[backgroundTask continueWithExecutor:[BFExecutor mainThreadExecutor] withSuccessBlock:^id(BFTask* task) {
id result = task.result;
// do something quick with the result - we're executing in the UI thread here
return nil
}];
PFQuery findInBackgroundWithBlock method executes the block with the default executor, so if you call that method from the main thread, there is a great chance that the block will also execute in the main thread.
In your case, although I know nothing about SpriteKit, I would fetch all sprites, then update the UI:
- (void)queryRenderAllUpdateOnce {
NSThread *currentThread = [NSThread currentThread];
NSLog(#"current thread is %# ", currentThread);
// replace the first task by [query findObjectsInBackground]
[[[BFTask taskFromExecutor:[Tasks backgroundExecutor] withBlock:^id _Nonnull{
NSLog(#"[%#] - Querying model objects", [NSThread currentThread]);
return #[#"Riri", #"Fifi", #"LouLou"];
}] continueWithExecutor:[BFExecutor immediateExecutor] withBlock:^id _Nullable(BFTask * _Nonnull task) {
NSLog(#"[%#] - Fetching sprites for model objects", [NSThread currentThread]);
NSArray<NSString *> * array = task.result;
NSMutableArray * result = [[NSMutableArray alloc] init];
for (NSString * obj in array) {
// replace with sprite
id sprite = [#"Rendered " stringByAppendingString:obj];
[result addObject:sprite];
}
return result;
}] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id _Nullable(BFTask * _Nonnull task) {
NSLog(#"[%#] - Update UI with all sprite objects: %#", [NSThread currentThread], task.result);
// TODO update the UI here.
return nil;
}];
}
But with this solution, all sprites are fetch (flattened ?) then the UI update. If you want to update the UI, every time a sprite is fetched, you could do something like this:
- (void)queryRenderUpdateMany {
NSThread *currentThread = [NSThread currentThread];
NSLog(#"current thread is %# ", currentThread);
[[[BFTask taskFromExecutor:[Tasks backgroundExecutor] withBlock:^id _Nonnull{
NSLog(#"[%#] - Querying model objects", [NSThread currentThread]);
return #[#"Riri", #"Fifi", #"LouLou"];
}] continueWithExecutor:[BFExecutor immediateExecutor] withBlock:^id _Nullable(BFTask * _Nonnull task) {
NSArray<NSString *> * array = task.result;
NSMutableArray * result = [[NSMutableArray alloc] init];
for (NSString * obj in array) {
BFTask *renderUpdate = [[BFTask taskFromExecutor:[BFExecutor immediateExecutor] withBlock:^id _Nonnull{
NSLog(#"[%#] - Fetching sprite for %#", [NSThread currentThread], obj);
return [#"Rendered " stringByAppendingString:obj];
}] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id _Nullable(BFTask * _Nonnull task) {
NSLog(#"[%#] - Update UI with sprite %#", [NSThread currentThread], task.result);
return nil;
}];
[result addObject: renderUpdate];
}
return [BFTask taskForCompletionOfAllTasks:result];
}] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id _Nullable(BFTask * _Nonnull task) {
NSLog(#"[%#] - Updated UI for all sprites", [NSThread currentThread]);
return nil;
}];
}
Here the middle task create a task that will complete once all renderUpdate tasks have completed.
Hope this help.
B
Related
I'm adding many block-operations to an operationsqueue in a for loop. In each operation I need to check on another thread if a condition is fulfilled. If the condition is fulfilled, all operations should be cancelled.
I made a sample code to show you my problem:
__block BOOL queueDidCancel = NO;
NSArray *array = [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10", nil];
NSOperationQueue *myQueue = [NSOperationQueue new];
myQueue.maxConcurrentOperationCount =1;
for (NSString *string in array) {
[myQueue addOperationWithBlock:^{
if (queueDidCancel) {return;}
NSLog(#"run: %#", string);
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if ([string isEqualToString:#"1"]) {
queueDidCancel = YES;
[myQueue cancelAllOperations];
}
});
}];
}
Expected output from NSLog:
run: 1
Output I got (it varies between 7 and 9):
run: 1
run: 2
run: 3
run: 4
run: 5
run: 6
run: 7
run: 8
I googled for hours, but I could not find a solution.
I think I found a solution. Here's the updated code:
NSArray *array = [NSArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10", nil];
NSOperationQueue *myQueue = [NSOperationQueue new];
myQueue.maxConcurrentOperationCount =1;
for (NSString *string in array) {
[myQueue addOperationWithBlock:^{
[myQueue setSuspended:YES];
NSLog(#"run: %#", string);
dispatch_async(dispatch_get_main_queue(), ^{
if (![string isEqualToString:#"1"]) {
[myQueue setSuspended:NO];
}
});
}];
}
Let me use more space. You need to sync access to your variable. It is the correct idea but you are using it incorrectly. You need a lock or an atomic ivar or something like that to sync access to it.
Then if you cancel in the dispatch_async bit it happens looooong after all the blocks executed. That is what your output shows. As mentioned in the comment, if you add a NSLog e.g.
dispatch_async(dispatch_get_main_queue(), ^{
if ([string isEqualToString:#"1"]) {
queueDidCancel = YES;
// Add here
NSLog(#"Going to cancel now");
[myQueue cancelAllOperations];
}
you will see what I mean. I expect that to typically execute deep into your array or even after all of the array finished executing.
But the biggest problem is your logic. You need some logic to cancel those blocks. Just messaging cancelAllOperations or setSuspended is not enough and blocks that are already running will keep on running.
Here is a quick example.
NSObject * lock = NSObject.new; // Use this to sync access
__block BOOL queueDidCancel = NO;
NSOperationQueue *myQueue = [NSOperationQueue new];
myQueue.maxConcurrentOperationCount =1;
for (NSString *string in array) {
// Here you also need to add some logic, e.g. as below
// Note the sync access
#synchronized ( lock ) {
if (queueDidCancel) { break; }
}
[myQueue addOperationWithBlock:^{
// You need to sync access to queueDidCancel especially if
// you access it from main and the queue or if you increase
// the concurrent count
// This lock is one way of doing it, there are others
#synchronized ( lock ) {
// Here is your cancel logic! This is fine here
if (queueDidCancel) {return;}
}
NSLog(#"run: %#", string);
dispatch_async(dispatch_get_main_queue(), ^{
if ([string isEqualToString:#"1"]) {
// Again you need to sync this
#synchronized ( lock ) {
queueDidCancel = YES;
}
// This is not needed your logic should take care of it ...
// The problem is that running threads will probably
// keep on running and you need logic to stop them
// [myQueue cancelAllOperations];
}
});
}];
}
Now this example does what yours does but with a bit more locking and a bit more logic and NO cancelAllOperations nor suspended = YESs. This will not do what you want as even with this running threads tend to run to completion and you need logic to stop it.
Also, in this example, I left the exit or cancel condition as is in the main thread. Again here this will probably mean nothing gets cancelled, but in real life you'd typically cancel from some UI e.g. a button click and then you'd do it as here. But you could cancel anywhere using the lock.
EDIT
Based on lots of comments here is another possible way.
Here you check inside the block and based on the check add another block or not.
NSOperationQueue * queue = NSOperationQueue.new;
// Important
queue.maxConcurrentOperationCount = 1;
void ( ^ block ) ( void ) = ^ {
// Whatever you have to do ... do it here
xxx
// Perform check
// Note I run it sync and on the main queue, your requirements may differ
dispatch_sync ( dispatch_get_main_queue (), ^ {
// Here the condition is stop or not
// YES means continue adding blocks
if ( cond )
{
[queue addOperationWithBlock:block];
}
// else done
} );
};
// Start it all
[queue addOperationWithBlock:block];
Above I use the same block every time which is also quite an assumption but you can change it easily to add different blocks. However, if the blocks are all the same you will only need one and do not need to keep on scheduling new blocks and then can do it as below.
void ( ^ block1 ) ( void ) = ^ {
// Some logic
__block BOOL done = NO;
while ( ! done )
{
// Whatever you have to do ... do it here
xxx
// Perform check
// Note I run it sync and on the main queue, your requirements may differ
dispatch_sync ( dispatch_get_main_queue (), ^ {
// Here the condition is stop or not
// YES means stop! here
done = cond;
} );
}
};
on IOS, I need to get metadata for a selected set of images. But since the images are backed up to iCloud, sometimes it may immediately return (cached) and sometimes it may take a second or two.
The for loop runs through quickly, I am able to wait for all of the images to be processed before I move forward. But they still are being fetched in parallel. How do I make the for loop run sequentially by waiting for the block to finish before moving on to next image.
// Step 4: Fetch Details like Metadata for this batch
-(void) getDetailsForThisBatchOfNewAssets:(NSMutableArray*) mArrBatchOfNewAssets
withCompletionHandler:(blockReturnsMArrAndMArr) blockReturns{
NSLog(#"%s with arraySize of %lu",__PRETTY_FUNCTION__, (unsigned long)[mArrBatchOfNewAssets count] );
long assetCount = [mArrBatchOfNewAssets count];
NSMutableArray *mArrNewAssetsAndDetails = [[NSMutableArray alloc] init];
NSMutableArray *mArrNewAssetFailed = [[NSMutableArray alloc] init];
if(assetCount == 0){
NSLog(#" Looks like there are no NEW media files on the device.");
return;
}
else
NSLog(#"found %ld assets in all that need to be backed up", assetCount);
dispatch_group_t groupForLoopGetDetails = dispatch_group_create();
for(long i = 0 ; i < assetCount; i++){
PHAsset *currentAsset = [[mArrBatchOfNewAssets objectAtIndex:i] objectForKey:#"asset"];
NSString *mediaIdentifier = [[[currentAsset localIdentifier] componentsSeparatedByString:#"/"] firstObject];
[mArrIdentifiersInThisBatch addObject:mediaIdentifier];
dispatch_group_enter(groupForLoopGetDetails);
[mediaManager getDetailedRecordForAsset:currentAsset
withCompletionHandler:^(NSMutableDictionary *mDicDetailedRecord, NSMutableDictionary *mDicRecordForError)
{
if(mDicRecordForError[#"error"]){
[mArrNewAssetFailed addObject:mDicRecordForError];
NSLog(#"Position %ld - Failed to fetch Asset with LocalIdentifier: %#, adding it to Failed Table. Record: %#",i,[currentAsset localIdentifier], mDicRecordForError);
} else {
[mArrNewAssetsAndDetails addObject:mDicDetailedRecord ];
NSLog(#"Position %ld - added asset with LocalIdentifier to mArrNewAssetsAndDetails %#",i,[currentAsset localIdentifier]);
}
dispatch_group_leave(groupForLoopGetDetails);
}];
} // end of for loop that iterates through each asset.
dispatch_group_notify(groupForLoopGetDetails, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSLog(#"Completed gathering details for this batch of assets for backup. Count : %lu and failed Media count: %lu",(unsigned long)[mArrNewAssetsAndDetails count], (unsigned long)[mArrNewAssetFailed count]);
blockReturns(mArrNewAssetsAndDetails,mArrNewAssetFailed);
});
}
I have looked through several questions on SO on this topic but still have not figured out how to make this run sequentially.
I don't want to do a "self call" for this method, because I'm already doing "self call" at another place before I reach this method and my code is now growing into too many notifications and catches because of that.
Assuming the completion handler of getDetailedRecordForAsset is called on a different thread, you can use a semaphore to block execution (Note: DO NOT DO this on the main thread) inside the loop while waiting for the completion handler.
Remove the dispatch group stuff, then, inside the loop:
create a semaphore right before calling getDetailedRecordForAsset like so: dispatch_semaphore_t semaphore = dispatch_semaphore_create( 0);
as the last statement of the completion handler call dispatch_semaphore_signal( semaphore);
immediately after calling getDetailedRecordForAsset, wait for the end of the completion handler with dispatch_semaphore_wait( semaphore, DISPATCH_TIME_FOREVER);
So the structure of the loop will look like:
for (assets)
{
... // get current asset, media identifier as above
dispatch_semaphore_t semaphore = dispatch_semaphore_create( 0);
[mediaManager getDetailedRecordForAsset:currentAsset
withCompletionHandler:^(NSMutableDictionary *mDicDetailedRecord, NSMutableDictionary *mDicRecordForError)
{
... // handle error or add asset details as above
dispatch_semaphore_signal( semaphore);
}
dispatch_semaphore_wait( semaphore, DISPATCH_TIME_FOREVER);
}
i am using magicalrecord in my app to manage coredata, every thing is perfect now but i am having an issue,i created 10k entities using this code:
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext * _Nonnull localContext) {
Person *person = [Person MR_createEntityInContext:localContext];
person.organization = [Organization MR_findfirstInContext:localContext];
person.name = name;
person.id = id;
person.age = age;
]};
after creating 10k records when i perform any change in database using magicalrecord it gets stuck for 4 or 5 seconds while saving to root context, which makes UI freez no matter if its on main thread or background thread.
Edited:
i have found the problem if i remove relation (which is organization) from save block it dont get stuck, if i fetch organization from out side the block and assign in inside the save block it throw an exception that organization is created in different context.
//case A
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
NSLog(#"current thread is main thread %d and thread is %#", [NSThread isMainThread], [NSThread currentThread]);
//some ManagedObject code
...
}];
//case B
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
NSLog(#"current thread is main thread %d and thread is %#", [NSThread isMainThread], [NSThread currentThread]);
//some ManagedObject code
...
}];
test this code, you will find case A always run at the MainThread,if you have 10K entities to store, the UI get stuck.
Look at this https://github.com/magicalpanda/MagicalRecord/blob/master/Docs/Saving-Entities.md
I am looking at the Ray Wenderlich tutorial on using dispatch queues to get notified when a group of tasks complete. http://www.raywenderlich.com/63338/grand-central-dispatch-in-depth-part-2
The first code shown under "Code that works" is straight from the tutorial. The Alert view(final completion block) get executed after all 3 downloads complete.
I tried to play around with it and moved the dispatch async down in the "Code that does not work" to see what will happen if dispatch_group_create() and dispatch_group_enter() happen on different queues. In this case, the dispatch_group_enter() does not seem to register because the dispatch_group_wait() immediately completes and alert view(final completion block) is executed even before all the downloads have completed.
Can someone explain whats happening in the second case? (This is just for my understanding of how dispatch group works and I realize thats its better to put the entire function in the global concurrent queue to avoid blocking the main thread).
Code that works
- (void)downloadPhotosWithCompletionBlock:(BatchPhotoDownloadingCompletionBlock)completionBlock
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^{
__block NSError *error;
dispatch_group_t downloadGroup = dispatch_group_create();
for (NSInteger i = 0; i < 3; i++)
{
NSURL *url;
switch (i) {
case 0:
url = [NSURL URLWithString:kOverlyAttachedGirlfriendURLString];
break;
case 1:
url = [NSURL URLWithString:kSuccessKidURLString];
break;
case 2:
url = [NSURL URLWithString:kLotsOfFacesURLString];
break;
default:
break;
}
dispatch_group_enter(downloadGroup);
__block Photo *photo = [[Photo alloc] initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
NSLog(#"Finished completion block for photo alloc for URL %# and photo is %#",url,photo) ;
dispatch_group_leave(downloadGroup);
}];
[[PhotoManager sharedManager] addPhoto:photo];
NSLog(#"Finished adding photo to shared manager for URL %# and photo is %#",url,photo) ;
}
dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); // 5
dispatch_async(dispatch_get_main_queue(), ^{
if (completionBlock) {
NSLog(#"Executing completion block after download group complete") ;
completionBlock(error);
}
}) ;
}) ;
}
EDITED Code that does not work with extra NSLog statements
Code that does not work
- (void)downloadPhotosWithCompletionBlock:(BatchPhotoDownloadingCompletionBlock)completionBlock
{
__block NSError *error;
dispatch_group_t downloadGroup = dispatch_group_create();
for (NSInteger i = 0; i < 3; i++)
{
NSURL *url;
switch (i) {
case 0:
url = [NSURL URLWithString:kOverlyAttachedGirlfriendURLString];
break;
case 1:
url = [NSURL URLWithString:kSuccessKidURLString];
break;
case 2:
url = [NSURL URLWithString:kLotsOfFacesURLString];
break;
default:
break;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0),^{
dispatch_group_enter(downloadGroup);
NSLog(#"Enetered group for URL %#",url) ;
__block Photo *photo = [[Photo alloc] initwithURL:url
withCompletionBlock:^(UIImage *image, NSError *_error) {
if (_error) {
error = _error;
}
NSLog(#"Finished completion block for photo alloc for URL %# and photo is %#",url,photo) ;
dispatch_group_leave(downloadGroup);
}];
[[PhotoManager sharedManager] addPhoto:photo];
NSLog(#"Finished adding photo to shared manager for URL %# and photo is %#",url,photo) ;
}) ;
}
NSLog(#"Executing wait statement") ;
dispatch_group_wait(downloadGroup, DISPATCH_TIME_FOREVER); // 5
dispatch_async(dispatch_get_main_queue(), ^{
if (completionBlock) {
NSLog(#"Executing completion block after download group complete") ;
completionBlock(error);
}
}) ;
}
The "dispatch_group_enter() does not seem to register" because it hasn't actually been called yet by the time that dispatch_group_wait() is called. Or, rather, it's not guaranteed to have been called. There's a race condition.
This isn't specifically about different queues. It's about concurrency and asynchronicity.
dispatch_async() just means "add a task to a list" with an implicit understanding that something, somewhere, somewhen will take tasks off of that list and execute them. It returns to its caller immediately after the task has been put on the list. It does not wait for the task to start running, let alone complete running.
So, your for loop runs very quickly and by the time it exits, it may be that none of the tasks that it has queued have started. Or, if any have started, it may be that they haven't finished entering the group.
Your code may complete its call to dispatch_group_wait() before anything has entered the group.
Usually, you want to be sure that all relevant calls to dispatch_group_enter() have completed before the call to dispatch_group_wait() is made. The easiest way to do that is to have them all happen synchronously in one execution context. That is, don't put calls to dispatch_group_enter() inside blocks that are dispatched asynchronously.
I have an app, where i use function FSMoveObjectToTrashSync. It works in background thread. I need ability for my app, to click on button to pause it or continue(if it paused) how i can make it?
Example of code:
NSMutableArray *fileArray = [NSMutableArray array withobjects:#"file1url", #"file2", #"file3", nil];
NSMutableArray *threadArray = [[NSMutableArray alloc] init];
-(void)myFunc{
for (NSURL *url in fileArray){
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:#selector(mySelectorWith:) object:url];
[thread start];
[threadArray addObject:thread];
}
}
-(void)mySelectorWith:(NSURL *) url{
FSRef source;
FSPathMakeRef((const UInt8 *)[[url path] fileSystemRepresentation], &source, NULL);
FSMoveObjectToTrashSync(&source, NULL, kFSFileOperationDefaultOptions);
}
PS:sorry for my english, i'm from Belarus... =(
One solution would be to replace the for loop on a single thread with an NSOperation subclass. Each operation should trash exactly one object; you then create one operation for each object you want to trash and put all of the operations on an NSOperationQueue.
The operation queue will run each operation on a thread, and it can even run multiple operations on multiple threads if it sees enough computing power laying around to do it.
An operation queue can be paused and resumed at will; when you suspend the queue, any operations in that queue that are already running will finish, but no more will start until you resume the queue.
You could use an NSConditionLock. An NSConditionLock is similar to a condition variable. It has a couple of basic methods, lockWhenCondition, and unlockWithCondition, and lock. A typical usage is to have your background thread waiting on the condition lock with "lockWhenCondition:", and the in you foreground thread to set the condition, which causes the background thread to wake up. The condition is a simple integer, usually an enumeration.
Here's an example:
enum {
kWorkTodo = 1,
kNoWorkTodo = 0
}
- (id)init {
if ((self = [super init])) {
theConditionLock = [[NSConditionLock alloc] initWithCondition: kNoWorkTodo];
workItems = [[NSMutableArray alloc] init];
}
}
- (void)startDoingWork {
[NSThread detachNewThreadSelector:#selector(doBackgroundWork) toTarget:self withObject:nil];
}
- (void)doBackgroundWork:(id)arg {
while (YES) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *items = nil;
[theConditionLock lockWhenCondition:kWorkTodo]; // Wait until there is work to do
items = [NSArray arrayWithArray:workItems]
[workItems removeAllObjects];
[theConditionLock unlockWithCondition:kNoWorkTodo];
for(id item in items) {
// Do some work on item.
}
[pool drain];
}
}
- (void)notifyBackgroundThreadAboutNewWork {
[theConditionLock lock];
[workItems addObject:/* some unit of work */];
[theConditionLock unlockWithCondition:kWorkTodo];
}
In this example, when startDoingWork is called doBackgroundWork: will start on a background thread, but then stop because there isn't any work to do. Once notifyBackgroundThreadAboutNewWork is called, then doBackgroundWork: will fire up and process the new work, and then go back to sleep waiting for new work to be available, which will happen the next time notifyBackgroundThreadAboutNewWork is called.