How to run multiple threads created by loop simultaneous using boost.thread?
I'm using learning the basic of boost.thread. So far, I can create each thread one by on开发者_运维知识库e manually to let them run at the same time. However, when creating by loop, it runs sequentially not concurrency anymore.
#include <iostream>
#include <boost/thread.hpp>
void workerFunc()
{
boost::posix_time::seconds workTime(3);
std::cout << "Worker: Running" << '\n';
boost::this_thread::sleep(workTime);
std::cout<< "Worker: Finished" << '\n';
}
int main()
{
std::cout << "main: startup" << '\n';
boost::thread workerThread(workerFunc);
std::cout << "main: waiting for thread" << '\n';
//these are ok
boost::thread t(workerFunc), t2(workerFunc), t3(workerFunc), t4(workerFunc);
t.join();
t2.join();
t3.join();
t4.join();
//these are not
for (int i = 0; i < 2; ++i)
{
boost::thread z(workerFunc);
z.join();
}
std::cout << "main:done" << '\n';
return 0;
}
for (int i = 0; i < 2; ++i)
{
boost::thread z(workerFunc);
z.join();
}
You are starting your thread and then immediately waiting for it to complete!
EDIT
One of several alternative hacks besides thread groups.
std::vector<boost::thread *> z;
for (int i = 0; i < 2; ++i)
z.push_back(new boost::thread(workerFunc));
for (int i = 0; i < 2; ++i)
{
z[i]->join();
delete z[i];
}
Ok I found the answer through the problem of someone else, as well as learn their problem:
How to make boost::thread_group execute a fixed number of parallel threads
Use shared_ptr
#include <iostream>
#include <boost/thread.hpp>
void workerFunc()
{
boost::posix_time::seconds workTime(3);
std::cout << "Worker: Running" << '\n';
boost::this_thread::sleep(workTime);
std::cout << "Worker: Finished" << '\n';
}
int main()
{
std::cout << "main: startup" << '\n';
std::vector<std::shared_ptr<boost::thread>> z;
for (int i = 0; i < 2; ++i) {
z.push_back(std::make_shared<boost::thread>(workerFunc));
}
for (auto t : z) {
t->join();
}
std::cout << "main:done" << '\n';
return 0;
}
Execute it
# g++ e.cpp -lboost_thread && ./a.out
main: startup
Worker: Running
Worker: Running
Worker: Finished
Worker: Finished
main:done
精彩评论