【问题标题】:Destruction order of the main thread and the use of pthread_key_create主线程的销毁顺序和pthread_key_create的使用
【发布时间】:2011-09-15 11:24:53
【问题描述】:

我想知道在传递析构函数时使用pthread_key_create。

我想要这样的东西:

static ComplexObject foo;

void workoncomplex(void *) {
    foo.dosomestuff();
}

static pthread_key_t pthreadkey;

void function_called_by_threads() {
    pthread_key_create(&pthreadkey, workoncomplex)
}

显然我遗漏了相当多的细节。

对于任何不是主线程的线程,这显然很好(提供锁定等),并且每当线程死亡时,我的workoncomplex 函数就会被调用并操作foo 对象。

我的问题是,这对主线程是否有效,因为显然pthreadkey 的析构函数调用发生在线程结束时,但它是否保证在静态被破坏之前运行?如果是这样,我是否必须检查我是否在主线程中并立即返回?或者我可以只对所有线程一视同仁,并假设我的静态对象仍然存在。

【问题讨论】:

    标签: c++ static pthreads destruction pthread-key-create


    【解决方案1】:

    在应用程序退出时不调用析构函数。它仅在线程退出时调用。

    如果您使用pthread_exit() 退出主线程,则将调用析构函数,但应用程序尚未关闭,因此使用static 变量是安全的。

    如果你调用exit()或者从main()返回,那么析构函数就不会被调用,所以static变量被销毁不是问题。使用atexit() 确保在从main() 返回或在调用exit() 时调用您的析构函数。

    【讨论】:

    • 谢谢。出于兴趣,您在哪里学习/阅读了此内容:“在应用程序退出时不调用析构函数。它仅在线程退出时调用。”
    • POSIX 规范和 linux 手册页给出了提示(例如,pthread_exit() 被描述为调用析构函数,并且当 main() 以外的线程从其线程函数返回时,它被隐式调用) .另外,我所写的内容符合我在 Linux、Solaris 和 MacOSX 上使用 POSIX TLS 析构函数的经验。
    猜你喜欢
    • 1970-01-01
    • 2019-05-02
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 2015-07-23
    • 1970-01-01
    相关资源
    最近更新 更多