- 1、本文档共5页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
g中的局部静态变量的初始化机制及线程安全
经典的meyers singleton模式想必大家都知道,其简要实现如下:template typename TT * T?::GetInstance(){??static?T ?instance;?return?instance;}局部静态变量在代码第一次执行到的时候才初始化,它不但可以延迟到全局对象初始化之后,甚至可以延迟到有人需要它的时候,才被构造出来,随需应变,挺帅吧?嗯,还有一些小问题,就是静态条件发生下局部静态变量可能被初始化多次(是吗?)、析构的时机不要把控等等(可参考 pattern hatching p61)。局部静态变量的析构,和全局对象一样,在main函数退出前进行(局部静态对象的析构是通过向std::atexit函数注册析构函数完成的,可参考modern c++ designer p147)。?那么这段代码在竞态条件发生时效果会如何呢?(实验证实g++的默认实现这段代码是线程安全的,想知道为啥,继续往下看)大家可以先看这个博文(/ewigkeit/archive/2010/07/21/5752323.aspx)c++ standard 原文如下(such an object is initialized the first time control passes through its declaration; such anobject is considered initialized upon the completion of its initialization. If the initialization exits by throwingan exception, the initialization is not complete, so it will be tried again the next time control enters thedeclaration. If control re-enters the declaration (recursively) while the object is being initialized, the behavioris undefined. )大体意思就是当有竟态条件发生的情况下,其实现是未定义的。??? 没得到什么可靠的结论,下面我们来做一段测试#include stdio.h#include iostream#include pthread.h???using namespace std;static int i = 0;class A{?? ?public:?? ? ? ?A()?? ? ? ?{?? ? ? ? ? ?cout A construct ++ i ?endl;?? ? ? ?}};?void* start_routine(void*){?? ?static A a;}?int main(int argc, char **argv){?? pthread_t id;?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? pthread_create(id, NULL, start_routine, NULL);?? sleep(-1);?? return 0;}测试结果:??看起来代码是线程安全的,但
文档评论(0)