直到最近,我的印象是,如果在產生它之後「分離」一個線程,即使在「主」線程終止之後線程仍然存在。pthread_detach問題
但是一個小實驗(下面列出)違背了我的信念。我期望分離線程繼續打印「從分離線程中講話」,即使在主要終止之後,但這似乎不會發生。應用程序顯然終止...
在「主要」問題後,「分離」線程是否死亡return 0?
#include <pthread.h>
#include <stdio.h>
void *func(void *data)
{
while (1)
{
printf("Speaking from the detached thread...\n");
sleep(5);
}
pthread_exit(NULL);
}
int main()
{
pthread_t handle;
if (!pthread_create(&handle, NULL, func, NULL))
{
printf("Thread create successfully !!!\n");
if (! pthread_detach(handle))
printf("Thread detached successfully !!!\n");
}
sleep(5);
printf("Main thread dying...\n");
return 0;
}
在其他線程運行時退出主線程並不是一個好主意;在任何情況下,從main()返回都會導致其他線程被殺害。 – MarkR 2011-05-18 11:52:14