gpt4 book ai didi

c - 为什么 fprintf 在线程中不起作用?

转载 作者:行者123 更新时间:2023-12-04 10:30:44 26 4
gpt4 key购买 nike

我正在使用 pthread_create 创建一个线程。

在我使用的线程函数中

fprintf(stdout, "text\n");

但这不会向控制台输出任何内容。 printf 也有同样的问题。我也试过刷新 stdout 缓冲区但没有成功。所以问题是如何从线程向控制台打印任何内容?

更新:

void *listen_t(void *arg){
fprintf(stdout, "test\n");
fflush(stdout);
}

int main(int argc, char **argv){
pthread_t tid;
int err;

err = pthread_create(&tid, NULL, &listen_t, &thread_params);
if (err != 0){
printf("\ncan't create thread :[%s]", strerror(err));
}
else{
printf("\n Thread created successfully\n");
}
return 0;
}

main 中的代码工作正常。但是线程没有输出任何东西

最佳答案

您缺少对 pthread_join 的调用:如果主程序在 printf 的输出到达控制台之前退出,您将看不到任何打印内容。

pthread_join(tid, NULL); 添加到您的示例中可修复输出:

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

void *listen_t(void *arg){
fprintf(stdout, "test\n");
fflush(stdout);
}

int main(int argc, char **argv){
pthread_t tid;
int err;

err = pthread_create(&tid, NULL, &listen_t, NULL);
if (err != 0){
printf("\ncan't create thread :[%d]", strerror(err));
}
else{
printf("\n Thread created successfully\n");
}
pthread_join(tid, NULL);
return 0;
}

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

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