我可以将dispatch_once_t谓词声明为成员变量而不是静态成员吗​​? [英] Can I declare dispatch_once_t predicate as a member variable instead of static?

查看:79
本文介绍了我可以将dispatch_once_t谓词声明为成员变量而不是静态成员吗​​?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每个实例只运行一次代码块.

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参考中,尚不清楚给我.

谓词必须指向存储在全局或静态中的变量 范围.使用具有自动或动态谓词的结果 存储空间未定义.

The predicate must point to a variable stored in global or static scope. The result of using a predicate with automatic or dynamic storage is undefined.

我知道我可以使用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谓词声明为成员变量而不是静态成员吗​​?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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