我正在学习boost.thread的基础知识。到目前为止,我可以手动逐个创建每个线程,让它们同时运行。但是,在通过循环创建时,它会依次运行而不是并发运行。
#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;
}
答案 0 :(得分:14)
for (int i = 0; i < 2; ++i)
{
boost::thread z(workerFunc);
z.join();
}
您正在开始线程,然后立即等待它完成!
修改强>
除线程组之外的几种替代黑客之一。
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];
}
答案 1 :(得分:1)
好的,我通过别人的问题找到答案,并了解他们的问题:
How to make boost::thread_group execute a fixed number of parallel threads
答案 2 :(得分:0)
使用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;
}
执行
# g++ e.cpp -lboost_thread && ./a.out
main: startup
Worker: Running
Worker: Running
Worker: Finished
Worker: Finished
main:done