JeremyLaurenson
JeremyLaurenson

Reputation: 979

OSX Objective C BOOL/vars thread safe?

Simple Question... is a global BOOL thread safe for me to use for thread synchronization? What other data types are actually safe, e.g. long longs..?

Eg: I have a task that runs - only want it to run once concurrently.

<pre>
BOOL isRunning;
unsigned long long progress;

if(!isRunning){
            dispatch_async(secondaryTask,^{
            [self doWork];
        });

-(void)doWork
{
isRunning=TRUE;
do a long op
isRunning=FALSE;
}
</pre>

Upvotes: 0

Views: 67

Answers (1)

Tommy
Tommy

Reputation: 100622

For the atomic types, exactly the same rules as ordinary C apply. So there's no guarantee of thread safety on any of them.

Use OSAtomic, NSConditionLock, the NSLocking protocol, serial dispatch queues, individual runloops, memory fences, spin locks, etc, to achieve thread safety.

For the trivial code given, which I accept is probably just for exposition, you'd most likely provide a completion handler block, which the asynchronous block would dispatch upon completion. If it's a serial queue, just push the task to it. Consider a dispatch group if you want synchronisation points within concurrent task groups.

Upvotes: 1

Related Questions