为什么 pthread_exit 表现得像 pthread_join?
Why pthread_exit acts like pthread_join?
代码:
void *PrintHello(void *threadid)
{
cout<<"Hello"<<endl;
sleep(3);
cout<<"Still PrintHello is alive"<<endl;
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
cout<<"Calling thread:"<<t<<endl;
pthread_create(&threads[0], NULL, PrintHello, NULL);
//pthread_join(threads[0],NULL);
cout<<"Main exits"<<endl;
pthread_exit(NULL);
}
为什么 pthread_exit(NULL)
在这里表现得像 pthread_join()
?即为什么退出 main
不破坏 printHello
线程并允许它继续?
pthread_exit()
仅终止调用线程。因此,当您从 main()
调用它时,它会终止主线程,同时允许进程继续。这符合预期。
如果您改为调用 exit()
(或通过返回隐式退出),它将终止整个过程,您将看到 printHello
也终止。
有很好的资源here但引用解释你的问题的部分:
Discussion on calling pthread_exit() from main():
There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads.
By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done.
代码:
void *PrintHello(void *threadid)
{
cout<<"Hello"<<endl;
sleep(3);
cout<<"Still PrintHello is alive"<<endl;
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
cout<<"Calling thread:"<<t<<endl;
pthread_create(&threads[0], NULL, PrintHello, NULL);
//pthread_join(threads[0],NULL);
cout<<"Main exits"<<endl;
pthread_exit(NULL);
}
为什么 pthread_exit(NULL)
在这里表现得像 pthread_join()
?即为什么退出 main
不破坏 printHello
线程并允许它继续?
pthread_exit()
仅终止调用线程。因此,当您从 main()
调用它时,它会终止主线程,同时允许进程继续。这符合预期。
如果您改为调用 exit()
(或通过返回隐式退出),它将终止整个过程,您将看到 printHello
也终止。
有很好的资源here但引用解释你的问题的部分:
Discussion on calling pthread_exit() from main():
There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads.
By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done.