【问题标题】:Why fprintf doesn't work in thread?为什么 fprintf 在线程中不起作用?
【发布时间】:2013-04-02 16:55:08
【问题描述】:

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

在我使用的线程函数内部

fprintf(stdout, "text\n");

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

更新:

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 中的代码运行良好。但是线程没有输出任何东西

【问题讨论】:

  • 请向我们展示一个演示问题的最小完整示例。
  • 线程运行是否分离?如果是这样,那么它就没有 STDOUT。
  • 如何将stdout 传递给线程?

标签: c multithreading io pthreads stdout


【解决方案1】:

您缺少对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;
}

【讨论】:

  • 请注意,您还应该在此处使用互斥锁,并在打印到控制台时锁定(以防您要使用多个线程进行打印)。
  • @ZarakiKenpachi:stdio 具有内部锁定。不需要另一层锁。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 2011-11-16
相关资源
最近更新 更多