我有一个应用程序,其中我在并行工作线程中执行昂贵的计算。为简单起见,我直接从这些线程将结果写入stdout。
这很好,直到我尝试更改一些东西以使代码运行更快。首先,我将std :: endl替换为“ \ n”,以防止每行之后出现刷新。我在主程序的init部分添加了以下几行:
std::cin.tie(nullptr);
std::ios_base::sync_with_stdio(false);
工作线程代码的基本结构如下:
while(true) {
// get data from job queue, protected by unique_lock on std::mutex
// process the data
// print results
{
std::lock_guard<std::mutex> lk(outputMutex_);
std::cout << "print many results" << "\n"; // was originally std::endl
}
}
由于这种“优化”,工人的产出有时会“混合”。即互斥体无法达到其预期目的。
为什么会这样?我的理解是,只有一个标准输出流缓冲区,并且即使释放互斥量之前未从该缓冲区清除输出,数据也会按顺序到达相应的缓冲区。但这似乎并非如此...
((我意识到在单独的线程中生成输出可能会更好,但随后我需要使用另一个队列将这些结果传回,这在这里似乎没有必要)
更新:也许我的帖子不够清楚。我不在乎结果的顺序。问题是(对于上面的示例)不是这样:
print many results
print many results
print many results
我有时会得到:
print many print many results
results
print many results
并且outputMutex_是所有工作线程共享的静态成员。
或者,您可以使用std :: flush告诉cout进行刷新:https://en.cppreference.com/w/cpp/io/manip/flush
尝试:
while(true) {
// get data from job queue, protected by unique_lock on std::mutex
// process the data
// print results
{
std::lock_guard<std::mutex> lk(outputMutex_);
std::cout << "print many results" << "\n" << std::flush;
}
}