有时c ++会给我带来很大的收获。我真的想不出为什么这样做/不起作用,如果你们中的任何一个人知道我会很高兴。
我在线程上每秒调用一次这个函数。
此代码WORKS(打印正在迭代的列表上的内容):
void DeltaList::print()
{
pthread_mutex_lock (&mutex);
printf("\n");
list<Delta*>::iterator it;
for(it=deltas.begin(); it!=deltas.end(); it++)
{
printf("%d ", (int) (*it)->timeleft);
}
pthread_mutex_unlock (&mutex);
}
这个没有(没有打印):
void DeltaList::print()
{
pthread_mutex_lock (&mutex);
//printf("\n");
list<Delta*>::iterator it;
for(it=deltas.begin(); it!=deltas.end(); it++)
{
printf("%d ", (int) (*it)->timeleft);
}
pthread_mutex_unlock (&mutex);
}
所以...?
答案 0 :(得分:3)
这与线程或C ++无关。操作系统正在缓冲输出,当stdout是控制台时,\n
隐式刷新缓冲区。如果您希望每次调用都立即显示其输出,请在循环后调用fflush(stdout)
。
答案 1 :(得分:0)
我想这是因为STDOUT被缓冲,而且打印\ n刷新缓冲区 - 请参阅SO on printf \n behaviour
答案 2 :(得分:0)
切换到使用std :: cerr作为实验我会打赌你每次打印都很好,因为缓冲了cout / printf(标准输出)时没有缓冲标准错误。在末尾放置一个std :: endl将缓冲刷新并为cout添加一个新行,该行也可以正常工作。你也可以简单地处理标准输出并在流上调用flush函数,以确保它打印到控制台,这类似。