[英]Main thread does not continue execution after pthread_create()
我使用pthread_create()
創建了一個線程。 新線程已成功創建,控件將傳遞給新創建的線程。 但是,似乎主線程不再執行了。 主線程處於無限循環中,永不退出。 以下是代碼片段:
void *start_routine(void)
{
printf("Start routine reached!\n");
fflush(stdout);
printf("Pthread returning!\n");
fflush(stdout);
return NULL;
}
void create_thread()
{
pthread_t newThread;
printf("Thread create reached!!\n");
fflush(stdout);
/* Create the new thread */
if((pthread_create(&newThread, NULL, start_routine , NULL)) != 0 ){
perror("pthread_create");
fflush(stdout);
}
printf("Thread create done!!\n");
fflush(stdout);
return;
}
輸出是:
Thread create reached!!
Start routine reached!
Pthread returning!
我沒有看到“Thread create done !!” 正在打印,程序只是停留在這一點上。
任何指針都會有所幫助。 謝謝!
它應該由你錯誤的start_routine
簽名引起。 pthread_create
的入口例程的標准簽名是void *(*start_routine)(void *)
。 在pthread_create
實現中,如果調用start_routine
,使用start_routine
的參數,在你的情況下, create_thread
為它提供值NULL
,因此,在pthread_create
,在調用start_routine
之前將NULL
壓入堆棧,但是, start_routine
不會恢復堆棧作為pthread_create
(完全是由pthread_create
調用的內部例程)期望,在start_routine
完成后,堆棧超出預期,並且可能遇到地址NULL
,這可能導致程序很快中止。
通過堆棧傳輸參數時會發生此問題。 要糾正它,只需將start_routine
更正為void *start_routine(void* args)
。 並且,在主線程中,調用pthread_join
來等待生成的線程完成,否則,資源泄漏將是一個潛在的問題。
如果您對Linux NPTL pthread_create
內部工作感興趣,可以訪問http://raison.gegahost.net/?p=91 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.