我正在尝试编写一个简单的程序测试多线程。我只是在交替的线程中打印一系列“x”和“O”。现在,如果我使用cout,屏幕上看不到输出。如果我使用fputc并将输出发送到stderr,它就可以正常工作。为什么在这里使用cout(输出到stdout)不起作用?
我的代码如下:
我的代码如下:
#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);
}
flush
刷新std::cout
吗? - Jarod42