@synchronized() 作为目标 C 中的单例方法有什么作用? [英] What does @synchronized() do as a singleton method in objective C?

查看:25
本文介绍了@synchronized() 作为目标 C 中的单例方法有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚创建了一个单例方法,我想知道函数@synchronized()是做什么的,因为我经常使用它,但不知道它的含义.

I just created a singleton method, and I would like to know what the function @synchronized() does, as I use it frequently, but do not know the meaning.

推荐答案

它声明了一个临界区 围绕代码块.在多线程代码中,@synchronized 保证在任何给定时间只有一个线程可以在块中执行该代码.

It declares a critical section around the code block. In multithreaded code, @synchronized guarantees that only one thread can be executing that code in the block at any given time.

如果您不知道它的作用,那么您的应用程序可能不是多线程的,并且您可能不需要使用它(特别是如果单例本身不是线程安全的).

If you aren't aware of what it does, then your application probably isn't multithreaded, and you probably don't need to use it (especially if the singleton itself isn't thread-safe).

添加一些 2011 年原始答案中没有的更多信息.

Adding some more information that wasn't in the original answer from 2011.

@synchronized 指令 防止多个线程进入任何受@synchronized 指令保护的代码区域引用同一个对象.传递给 @synchronized 指令的对象是用作锁"的对象.如果使用不同的对象作为锁,两个线程可以在同一个代码保护区域,也可以使用同一个对象作为锁来保护两个完全不同的代码区域.

The @synchronized directive prevents multiple threads from entering any region of code that is protected by a @synchronized directive referring to the same object. The object passed to the @synchronized directive is the object that is used as the "lock." Two threads can be in the same protected region of code if a different object is used as the lock, and you can also guard two completely different regions of code using the same object as the lock.

另外,如果你碰巧传递了 nil 作为锁对象,则根本不会获取锁.

Also, if you happen to pass nil as the lock object, no lock will be taken at all.

这篇关于@synchronized() 作为目标 C 中的单例方法有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆