您的位置:首页 > 其它

关于@synchronized(self)的用法

2013-08-19 22:11 302 查看
@synchronized 的作用是创建一个互斥锁,保证此时没有其它线程对self对象进行修改。这个是objective-c的一个锁定令牌,防止self对象在同一时间内被其它线程访问,起到线程的保护作用。
一般在公用变量的时候使用,如单例模式或者操作类的static变量中使用。
# import "NetworkManager.h"
static NetworkManager *network = nil;
@implementation NetworkManager
+ (NetworkManager *)getNetworkInstance{ @synchronized(self){  if (nil == network){   network = [[NetworkManager alloc] init];  { } return network;}
英文文档:Using the @synchronized Directive(指令)
The @synchronized directive is a convenient way to create mutex locks(互斥锁) on the fly inObjective-C code. The @synchronized directive does what any other mutex lock woulddo—it prevents(预防) different threads from acquiring the same lock at the same time. Inthis case, however, you do not have to create the mutex or lock object directly. Instead, you simply use any Objective-C object as a lock token with @synchronized。
The object passed to the @synchronized directive is a unique identifier used to distinguish theprotected block. If you execute the preceding method in two different threads, passing a different objectfor the anObj parameter on each thread, each would take its lock and continue processing without being blocked by the other. If you pass the same object in both cases, however, one of the threads would acquire the lock first and the other would block until the first thread completed the critical section.
As a precautionary measure, the @synchronized block implicitly adds an exception handler to theprotected code. This handler automatically releases the mutex in the event that an exception is thrown.This means that in order to use the @synchronized directive, you must also enable Objective-C exception handling in your code. If you do not want the additional overhead caused by the implicitexception handler, you should consider using the lock classes.

For more information about the @synchronized directive, see The Objective-C ProgrammingLanguage.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: