关于c ++:主线程退出后线程访问共享变量

thread access shared variables after main thread exit

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class A {
 public:
  A() { printf("Constructing A
"
); }
  ~A() { printf("Destructing A
"
); }
  void printSomething() { printf("A is printing
"
); }
}

A a;

void thread_func() {
  printf("begin thread.
"
);
  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;
}

该程序产生:

1
2
3
4
bash$ ./a.out
Constructing A
Destructing A
bash$

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

还有另一个困惑,为什么主线程退出时会清除所有资源? 看起来全局变量的生存期仅取决于主线程吗?


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

但是,main()可以调用pthread_exit()-并且不会终止该过程。 根据Linux pthread_exit()手册页:

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.


线程本身没有自己的内存,但是与其父进程共享内存。 他们与父母息息相关。 因此,无论何时父进程死亡,其子线程也会被杀死。