问题描述
Latelly我一直在使用多线程编码,经过一段时间的写作,我意识到如果我在不同的boost ::线程中使用std :: cout,输出将没有一个逻辑顺序,程序, m测试是这样的:
Latelly I've been working with multi-thread coding, after a while writing I realized that if I used std::cout in different boost::threads, the output would came without a logical order, the program that I'm testing is something like:
#include <boost/thread/thread.hpp>
#include <iostream>
int my01( void )
{
std::cout << "my01" << std::endl;
return 0;
}
/* my02, my03 and my04 are the same with different outputs*/
[...]
int main( void )
{
boost::thread t1(&my01);
boost::thread t2(&my02);
boost::thread t3(&my03);
boost::thread t4(&my04);
while(!t1.joinable() || !t2.joinable() || !t3.joinable() || !t4.joinable());
t1.join();
t2.join();
t3.join();
t4.join();
std::cout << "The end!" << std::endl;
getchar();
return 0;
}
输出通常是):
And the output is usually like (it changes):
考虑到这个问题,我想创建一个单线程管理所有输出,因此它们的顺序如下:
With this issue in mind I was thinking of creating a single thread to manage all of the outputs, so they would be in order like:
哪个是写这样的线程或管理这些输出的最佳方式?
请阅读此问题的答案:是cout同步/线程安全吗?
Ps:我使用Visual C ++ 2010 Express和我的cpu有8个不同的内核。 br>
谢谢您的时间!
推荐答案
首先,避免所有显式线程管理,而是使用 std :: async
以某些任意数量的单独线程启动任务。
第二,不是在线程本身中执行I / O,而是要创建结果,并连续地执行输出。这意味着线程函数只是创建一些数据,并留给调用者来写出来:
// warning: untested code
std::string process(int value) {
std::ostringstream buffer;
buffer << "my" << std::setfill('0') << std::setw(2) << value;
return buffer.str();
}
Then we need to launch invoke four copies of that asychronously:
std::vector<std::future<std::string> > results;
for (int i=0; i<4; i++)
results.push_back(std::async(process, i));
Then we wait for the results and print them out in order:
for (int i=0; i<4; i++)
std::cout << results[i].get();
这篇关于同步STD cout输出多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!