Does it makes sense to make atomic a BOOL flag in multithreading programming Does it makes sense to make atomic a BOOL flag in multithreading programming multithreading multithreading

Does it makes sense to make atomic a BOOL flag in multithreading programming


The answer is entirely dependent on the answer to the question:

"do you need to run doIt exactly once for each time the main thread sets the shouldDoIt flag?"

If the answer to that question is "yes" then your code will not work because the main thread might set shouldDoIt to YES after you have started doIt but before you have reset the flag.

If the answer is "no", in this narrow case, what you have is sort of OK excepting the fact that in a multi CPU configuration, the flag might be cached in such a way that the other thread does not immediately see the change. So you probably at least want to use OSAtomicTestAndClearBarrier() and OSAtomicTestAndSetBarrier() which are as low level, hence as fast as you can get.

However, I'm sceptical that you need to do this. I think you might find refactoring the design in some way will get better results depending on what you are trying to do in doIt, do stuff and do more stuff.


On may thread you have an BOOL that you want to set to no after you do some job in back thread

[NSThread detachNewThreadSelector:@selector(backThreadAction:) toTarget:self withObject:nil];-(void) backThreadAction:(id*)someObject{    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    //do stuff here    [self performSelectorOnMainThread:@selector(didFinishBackThreadAction:) withObject:nil waitUntilDone:NO];    [pool release];}-(void) didFinishBackThreadAction:(id *)someObject{   //set your bool to no}


Read first the Threading Programming Guide from Apple and I think you need an NSLockbut be careful you can get an deadlock.Good Luck