我正在尝试一个简单的程序来测试多线程。我只是在备用线程中打印一系列“x”和“O”。现在,如果我使用cout,屏幕上不会显示任何输出。如果我使用fputc并输出到stderr,它可以正常工作。为什么cout(输出到stdout)不在这里工作?下面为什么cout不能与pthreads一起使用?
我的代码给出:
#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);
}
你尝试'冲洗''std :: cout'? – Jarod42
请尝试打印到'stdout'。 –
@Nawaz std :: cout是线程安全的。 – Galik