gpt4 book ai didi

c - 为什么 printf 在多线程程序中不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:33 25 4
gpt4 key购买 nike

我有一个多线程程序,无法弄清楚为什么 printf 不能按预期工作。

这是我的代码:

#include <pthread.h>
#include <stdio.h>

void *Msg(void *arg)
{
pthread_t x;
x= pthread_self();
printf("x=%ld\n", x);
printf("This MSG from a thread \n");
pthread_exit((void*)0);
}



int main()
{
pthread_t n;
pthread_create(&n, NULL, Msg, NULL);
pthread_create(&n, NULL, Msg, NULL);
printf("Mother thread\n");
return 0;
}

我的问题是为什么它不打印句子“This MSG...”。

最佳答案

在主线程退出之前,您应该加入线程以让它们有机会运行。当一个线程退出进程时,所有其他线程都会被杀死。

尝试:

pthread_join(n, NULL);
return 0;

关于c - 为什么 printf 在多线程程序中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8382905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com