3

我正在创建一个线程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 中的代码工作正常。但是线程不输出任何东西

4

1 回答 1

4

您错过了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;
}
于 2013-04-10T17:51:45.890 回答