【iOS开发】---- Using the @synchronized Directive(使用同步指令)
来源:互联网 发布:网络语言暴力的后果 编辑:程序博客网 时间:2024/04/29 03:22
@synchronized指令可以在Objective-C中方便快速的创建一个互斥锁的方法。@synchronized指令可以做到任何其他互斥锁所做的--它可以防止不同的线程同时获取相同的锁。然而,在这种情况下,你不直接创建互斥或锁定对象。相反,你只需使用任何Objective-C的对象作为一个锁定令牌,如下面的例子所示:
- (void)myMethod:(id)anObj{ @synchronized(anObj) { // Everything between the braces is protected by the @synchronized directive. }}
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 from acquiring the same lock at the same time. In this 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, as shown in the following example:
- (void)myMethod:(id)anObj{ @synchronized(anObj) { // Everything between the braces is protected by the @synchronized directive. }}
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. 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 the protected 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 implicit exception handler, you should consider using the lock classes.
For more information about the @synchronized
directive, see The Objective-C Programming Language.
- 【iOS开发】---- Using the @synchronized Directive(使用同步指令)
- JSP指令(directive)
- Directive(指令)
- 自定义指令(directive)
- Vue 指令(Directive)
- Angularjs自定义指令(directive)
- 使用@synchronized指令
- Angular 指令(Directive)属性型指令
- AngularJS 的 ngSwitch 指令 (directive) 使用陷阱
- anjular js ---directive常用指令使用
- 线程同步的使用(synchronized)
- 使用synchronized同步
- AngularJS实例详解Directive(指令)机制
- AngularJS 详解Directive(指令)机制
- angularjs 指令(directive)详解(1)
- angularjs 指令(directive)详解(2)
- 详说Angular之指令(directive)
- AngularJS 学习笔记 -- 指令(Directive)
- 基于NS2的绿色云计算模拟器(GreenCloud)
- c# WinForm 创建与读写配置文件
- Redis设计与实现读书笔记——简单动态字符串
- Android ListView 列表视图
- Cannot load JDBC driver class 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
- 【iOS开发】---- Using the @synchronized Directive(使用同步指令)
- Launcher中锁定图标位置
- SET XACT_ABORT各种用法及显示结果
- UIControl 的几个事件的说明
- tk组件学习---text
- IT业的下一次革命:软件定义网络
- Android 4.0.3 源代码结构分析(一)
- Android 检测是否连接蓝牙耳机
- Nginx 限制IP并发数及速度