【发布时间】:2016-08-22 10:04:33
【问题描述】:
我正在尝试一个简单的程序来测试多线程。我只是在备用线程中打印一系列“x”和“O”。现在,如果我使用 cout ,屏幕上看不到任何输出。如果我使用 fputc 并输出到 stderr ,它工作正常。为什么 cout(输出到标准输出)在这里不起作用?
我的代码如下:
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
using namespace std;
static int count;
void* print_xs(void *unused)
{
while(1)
{
if (count >=100) break;
if (count%2==0)
{
count++;
cout<<"X="; // no output here
fputc('X',stderr); // works !
}
else
{
sleep(1);
}
}
return NULL;
}
int main()
{
pthread_t tid;
pthread_create(&tid,NULL,&print_xs, NULL);
while(1)
{
if (count >=100) break;
if (count%2!=0)
{
count++;
cout<<"O="; // no output here
fputc('O',stderr); // works !
}
else
{
sleep(1);
}
}
pthread_join(tid,NULL);
return (0);
}
【问题讨论】:
-
你试过
flushstd::cout吗? -
尝试打印到
stdout。 -
@Nawaz std::cout 是线程安全的。
-
@Galik:是的。自 C++11 以来,它发生了变化。谢谢指正。
-
另外:你的代码对我有用(Linux GCC 6.1.1)