关于@synchronized(self)的用法
来源:互联网 发布:sql视图添加数据 编辑:程序博客网 时间:2024/06/03 15:40
@synchronized 的作用是创建一个互斥锁,保证此时没有其它线程对self对象进行修改。这个是objective-c的一个锁定令牌,防止self对象在同一时间内被其它线程访问,起到线程的保护作用。 一般在公用变量的时候使用,如单例模式或者操作类的static变量中使用。
原文出处:http://blog.163.com/hongbin89@126/blog/static/112853955201302794741414/# 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 in Objective-C code. The @synchronized directive does what any other mutex lock would do—it prevents(预防) different threads fromacquiring the same lock at the same time. In this case, however, you do nothave to create the mutex or lock object directly. Instead, you simply use anyObjective-C object as a lock token with @synchronized。
The object passed to the @synchronized directive is a unique identifier used to distinguish the protected block. If you execute the preceding method in two different threads, passing a different object for the anObj parameter on each thread, each would take its lock and continue processing without being blocked by the other. Ifyou 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 the protected code. This handler automatically releases the mutex in theevent that an exception is thrown. This means that in order to use the@synchronized directive, you must also enable Objective-C exception handling inyour 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-CProgramming Language.
- 关于@synchronized(self)的用法
- 关于@synchronized(self)的用法
- 关于@synchronized(self)的用法
- 关于@synchronized(self)的用法
- 关于@synchronized(self)的用法
- 关于@synchronized(self)的用法
- 关于@synchronized(self)的用法
- 关于@synchronized(self)的用法
- @synchronized(self)的用法
- 关于 @synchronized(self) 的理解
- @synchronized(self)的涵义
- @synchronized(self) 的作用
- @synchronized(self)的作用
- iphone关于self.用法的一些总结
- 关于self.用法的一些总结
- iphone关于self.用法的一些总结
- 关于self.用法的一些总结
- 关于 self.用法的一些总结
- Css_text
- 解决win10系统提示“计算机内存不足”的问题?
- android sdk使用镜像更新
- POJ 3450--Corporate Identity【KMP && 枚举】
- mt7620a上tf卡驱动的支持
- 关于@synchronized(self)的用法
- Linux下安装Mysql(RPM安装)
- 畅通工程续
- 3.1Android中,Sqlite轻量级数据库的使用
- Spring 学习笔记(六)——WebFlow
- 【C语言连载三】-----------运算符、Scanf函数
- 我的openwrt学习笔记(一):OpenWrt简介
- AltiumDesigner98——PCB中各层的作用
- 《Java设计模式》之责任链模式