如果您想要的只是一个简单的全局锁,请查看 NSLock。
例如:
static NSLock * myGlobalLock = [[NSLock alloc] init];
if ([myGlobalLock tryLock]) {
// do something
[myGlobalLock unlock];
}
else {
// couldn't acquire lock
}
但是,这会导致性能损失,因为它需要内核调用。如果你想序列化对资源的访问,使用 Grand Central Dispatch 和私有队列会执行得更好——这些都是在不需要内核中断的情况下调度的。
例如:
// 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
});
调度队列是非常棒的东西,如果你正在进入 iOS 开发,你应该学习如何使用它们以使应用程序具有出色的性能。
除了 NSLock 之外,还有不同类型的锁。阅读线程编程参考中的同步以获取更多信息...
线程编程参考:
https ://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Multithreading/Introduction/Introduction.html#//apple_ref/doc/uid/10000057i
NSLock 参考:
https ://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSLock_Class/Reference/Reference.html
Grand Central Dispatch 参考:https ://developer.apple.com/library/ios/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html