【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.    }}


       传递给@synchronized指令的对象是一个用来区分保护块(protected block)的唯一标识符。如果在两个不同的线程中执行上面的方法,在每个线程anObj参数传递一个不同的对象,每个线程会拿到它的锁,并且继续处理而不会被另一个线程锁住。如果在两个线程中传递了同一个对象,那么第一个线程就会先获得这个锁,另一个线程就会被锁住直到第一个线程完成了临界区域。

       作为一项预防措施, @ synchronized块的隐式添加一个异常处理程序的保护代码。此处理程序会自动释放互斥事件,抛出一个异常。这意味着,为了使用@synchronized,你还必须在你的代码中使用Objective-C的异常处理。如果你不想要由隐含的异常处理程序造成额外的开销,你应该考虑使用锁类(lock classes)。

       更多同步指令信息,请参考The Objective-C Programming Language。




英文文档:

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.


原创粉丝点击