为什么PTHREAD_CREATE无法100%的时间工作?
我最近正在学习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
预期的结果是这是Sub_Routine
两次。好吧,这是发生的,但不是100%的时间。有什么特别的原因吗?
I am recently learning about threads in C, and I have noticed something I consider weird.
Let's take the next code:
#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);
}
I use this command line to compile my program:
gcc -Wall -Wextra -Werror -pthread pthreads.c
The expected result is to print This is a sub_routine
two times. Well that happens but not 100% of the times. Is there any particular reason for that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当
main
返回时,即使其他线程正在运行,它也会退出程序。因此,您产生的线程可能不会在主线程返回之前无法到达printf
,在这种情况下,在您看到两个消息之前,程序结束。解决此问题的一种方法是将调用添加到
pthread_join
main 的结尾,告诉程序等待您创建的线程在主返回之前完成运行。这将确保您始终看到两个打印输出。When
main
returns, it exits the program even if other threads are running. Therefore, it’s possible for the thread you spawned to not get to theprintf
before the main thread returns, in which case the program ends before you’ll see both messages.One way to address this is to add a call to
pthread_join
at the end ofmain
to tell the program to wait for the thread you created to finish running before main returns. That will ensure you always see two printouts.在主线程的末尾(返回之前)添加pthread_join(thread,null),以加入线程“ sub_routine”
您的代码的修改版本正常工作:
Add pthread_join(thread, NULL) at the end (just before return) of the main thread to join the thread "sub_routine"
The modified version of your code works properly: