gpt4 book ai didi

c++ - 主线程退出后线程访问共享变量

转载 作者:太空狗 更新时间:2023-10-29 23:01:41 27 4
gpt4 key购买 nike

如果分离线程在调用线程退出并销毁共享变量后访问共享变量(例如全局变量),在多线程 C++ 程序中会发生什么情况?

class A {
public:
A() { printf("Constructing A\n"); }
~A() { printf("Destructing A\n"); }
void printSomething() { printf("A is printing\n"); }
}

A a;

void thread_func() {
printf("begin thread.\n");
sleep(3); // make sure main thread exit first
a.printSomething();
printf("ending thread");
}

int main(int argc, char** argv) {
std::thread t(thread_func);
t.detach();

return 0;
}

程序产生:

bash$ ./a.out
Constructing A
Destructing A
bash$

似乎主线程创建了全局变量 a 并在退出时将其销毁。如果分离的子线程试图访问这个全局变量,那么 3 秒后会发生什么?

还有一个疑惑是,为什么主线程退出的时候会清空所有资源?看起来全局变量的生命周期只依赖于主线程?

最佳答案

进程在 main() 返回时退出,或者任何线程调用 exit()_exit()

但是,main() 可以调用 pthread_exit() - 这将不会终止进程。根据 Linux pthread_exit() man page :

When a thread terminates, process-shared resources (e.g., mutexes, condition variables, semaphores, and file descriptors) are not released, and functions registered using atexit(3) are not called.

After the last thread in a process terminates, the process terminates as by calling exit(3) with an exit status of zero; thus, process-shared resources are released and functions registered using atexit(3) are called.

关于c++ - 主线程退出后线程访问共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30699618/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com