@synchronized()作为目标C中的单例方法有什么作用? [英] What does @synchronized() do as a singleton method in objective 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.
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屋!