[英]Destruction order of the main thread and the use of pthread_key_create
I was wondering about the use of pthread_key_create
while passing in a destructor function. 我想知道在传递析构函数时使用
pthread_key_create
。
I wanted to have something like this: 我想要这样的东西:
static ComplexObject foo;
void workoncomplex(void *) {
foo.dosomestuff();
}
static pthread_key_t pthreadkey;
void function_called_by_threads() {
pthread_key_create(&pthreadkey, workoncomplex)
}
Obviously I've left out a fair amount of detail. 显然,我省略了很多细节。
For any thread that isn't the main thread, this is obviously fine (provided locking etc.), and whenever a thread dies, my workoncomplex
function gets called and manipulates the foo
object. 对于不是主线程的任何线程,这显然都很好(提供了锁定等),并且每当线程死亡时,都会调用我的
workoncomplex
函数并操作foo
对象。
My question is, is this valid for the main thread, as obviously the pthreadkey
's calling of the destructor happens at thread wind down, but is it guaranteed to run before the statics are destructed? 我的问题是,这对主线程是否有效,因为显然销毁线程的
pthreadkey
调用了析构函数,但是可以保证在析构静态变量之前运行它吗? If so, would I have to check if I'm in the main thread and just return immediately? 如果是这样,我是否必须检查我是否在主线程中并立即返回? Or can I just treat all threads the same and assume my static objects will still be around.
或者我可以将所有线程都一样对待,并假设我的静态对象仍然存在。
The destructor function is not called on application exit. 在应用程序退出时不调用析构函数。 It is only called when a thread exits.
仅在线程退出时调用。
If you exit the main thread with pthread_exit()
then the destructor function will be called, but the application is not yet being shut down so it is safe to use the static
variables. 如果使用
pthread_exit()
退出主线程,则将调用析构函数,但是该应用程序尚未关闭,因此可以安全地使用static
变量。
If you call exit()
or return from main()
then the destructor function will not be called, so the fact that the static
variables are destroyed is not a problem. 如果调用
exit()
或从main()
返回,则不会调用析构函数,因此static
变量被销毁的事实不是问题。 Use atexit()
to ensure that your destructor function is called on return from main()
or on a call of exit()
. 使用
atexit()
以确保在从main()
返回或调用exit()
调用析构函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.