我正在尝试一个简单的程序来测试多线程。我只是在交替线程中打印一系列“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);
}
最佳答案
由于std::cout
是缓冲流,因此需要flush将其发送到标准输出。
只需尝试类似:
cout<< "O=";
cout.flush();
那应该工作。补充笔记
std::cout
在C++ 03和更低版本中不是线程安全的。用mutex保护该对象可能很有用。自C++ 11标准以来,这可能不是问题。
FDIS在§27.4.1[iostream.objects.overview]中指出以下内容:
这意味着如果没有互斥锁,则可以确保对象在数据争用上下文中不会损坏。但是输出重叠的问题仍然存在。因此,如果您确定每行打印时都不会被另一个线程重叠,那么您仍然需要一个互斥锁。