First of all, you might consider avoiding all the explicit thread management, and instead use std::async
to launch your tasks in some arbitrary number of separate threads.
Second, instead of doing the I/O in the threads themselves, you want to create results, and do the output itself serially. This means the thread function just creates some data, and leaves it to the caller to actually write that out:
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 four copies of that asychronously:
std::vector<std::future<std::string> > results;
for (int i=0; i<4; i++)
results.push_back(std::async(std::launch::async, process, i));
Then we get the results and print them out in order:
for (auto &r : results)
std::cout << r.get() << "
";
Putting those together, we could get code like this:
#include <string>
#include <iostream>
#include <thread>
#include <future>
#include <sstream>
#include <vector>
#include <iomanip>
std::string process(int value) {
std::ostringstream buffer;
buffer << "my" << std::setfill('0') << std::setw(2) << value;
return buffer.str();
}
int main() {
std::vector<std::future<std::string>> rets;
for (int i=0; i<4; i++)
rets.push_back(std::async(std::launch::async, process, i));
for (auto & t : rets) {
t.wait();
std::cout << t.get() << "
";
}
}
I should add one minor point: I'm basing this on standard C++11 future
s. I believe the basic idea should also work with Boost future
s (upon which the standard was based) but I haven't tested that. I'd expect that some minor adjustments (e.g., to names) will be needed to work with Boost's futures.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…