[英]Why pthread_create does not work 100% of the times?
我最近在學習 C 中的線程,我注意到一些我認為很奇怪的東西。 讓我們看下一段代碼:
#include <stdio.h>
#include <pthread.h>
void *sub_routine(void *p)
{
p = NULL;
printf("This is a sub_routine\n");
return (NULL);
}
int main(int argc, char **argv)
{
void *p;
pthread_t thread;
if (argc < 1)
return (0);
p = argv[1];
pthread_create(&thread, NULL, sub_routine, NULL);
sub_routine(p);
return (0);
}
我使用這個命令行來編譯我的程序:
gcc -Wall -Wextra -Werror -pthread pthreads.c
預期的結果是打印This is a sub_routine
兩次。 嗯,這種情況會發生,但不是 100% 的時間。 有什么特別的原因嗎?
當main
返回時,即使其他線程正在運行,它也會退出程序。 因此,您生成的線程可能在主線程返回之前沒有到達printf
,在這種情況下,程序在您看到兩條消息之前就結束了。
解決此問題的一種方法是在main
的末尾添加對pthread_join
的調用,以告訴程序在 main 返回之前等待您創建的線程完成運行。 這將確保您始終看到兩個打印輸出。
在主線程的末尾(就在返回之前)添加 pthread_join(thread, NULL) 以加入線程“sub_routine”
您的代碼的修改版本可以正常工作:
#include <stdio.h>
#include <pthread.h>
void *sub_routine(void *p)
{
p = NULL;
printf("This is a sub_routine\n");
return (NULL);
}
int main(int argc, char **argv)
{
void *p;
pthread_t thread;
if (argc < 1)
return (0);
p = argv[1];
pthread_create(&thread, NULL, sub_routine, NULL);
sub_routine(p);
pthread_join(thread, NULL);
return (0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.