问题描述
我希望每个实例只运行一次代码块.
I want to run a block of code only once per instance.
我可以将dispatch_once_t谓词声明为成员变量而不是静态变量吗?
Can I declare dispatch_once_t predicate as a member variable instead of static variable?
在 GCD参考中,尚不清楚给我.
我知道我可以使用dispatch_semaphore_t和一个布尔标志来做同样的事情.我很好奇.
I know I can use dispatch_semaphore_t and a boolean flag to do the same thing. I'm just curious.
推荐答案
dispatch_once_t
不能是实例变量.
dispatch_once()
的实现要求dispatch_once_t
为零,并且从未为非零.以前非零的情况将需要其他内存屏障才能正常工作,但是dispatch_once()
出于性能原因忽略了这些屏障.
The implementation of dispatch_once()
requires that the dispatch_once_t
is zero, and has never been non-zero. The previously-not-zero case would need additional memory barriers to work correctly, but dispatch_once()
omits those barriers for performance reasons.
实例变量被初始化为零,但它们的内存可能先前已存储了另一个值.这使它们对于dispatch_once()
使用是不安全的.
Instance variables are initialized to zero, but their memory may have previously stored another value. This makes them unsafe for dispatch_once()
use.
这篇关于我可以将dispatch_once_t谓词声明为成员变量而不是静态成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!