Reputation: 2313
I have a pretty simple question that I'm hoping someone can point me in the right direction on. I'm a java developer trying to figure out the correct objective C approach to a global lock. I have a class which is instantiated in several place. Each instance reads and writes to a single common file. As such, I need to make sure all method calls in this class are atomic. In java this would be done as follows:
static Object lock
public void writeToFile(){
synchronized(lock){
//thread safe code goes here
}
}
The static identifier would mean that the lock object is shared across all instances and would as such be threadsafe. Unfortunately since iOS doesn't have class variables in the same way, I'm not sure what the best way to achieve this functionality is.
Upvotes: 2
Views: 2026
Reputation: 1724
If all you want is a simple global lock, look at NSLock.
eg:
static NSLock * myGlobalLock = [[NSLock alloc] init];
if ([myGlobalLock tryLock]) {
// do something
[myGlobalLock unlock];
}
else {
// couldn't acquire lock
}
However, this is going to incur a performance penalty because it requires a kernel call. If you want to serialize access to a resource, using Grand Central Dispatch and a private queue is going to perform much better--these are scheduled without requiring a kernel interrupt.
eg:
// alloc a dispatch queue for controlling access to your shared resource
static dispatch_queue_t mySharedResourceQueue = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
mySharedResourceQueue = dispatch_queue_create("com.myidentifier.MySharedResourceQueue", DISPATCH_QUEUE_SERIAL); // pick a unique identifier
});
// don't forget to call dispatch_release() to clean up your queue when done with it!
// to serialize access to your shared resource and block the current thread...
dispatch_sync(mySharedResourceQueue, ^{
// access my shared resource
});
// or to access it asynchronously, w/o blocking the current thread...
dispatch_async(mySharedResourceQueue, ^{
// access my shared resource
});
Dispatch queues are highly awesome things and if you're getting in to iOS development you should learn how to use them in order to make apps with great performance.
There are different types of locks besides NSLock too. Read up on synchronization in the Threaded Programming reference for more info...
Threaded Programming reference: https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html#//apple_ref/doc/uid/10000057i
NSLock reference: https://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSLock_Class/Reference/Reference.html
Grand Central Dispatch reference: https://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html
Upvotes: 5