使用下面的代码,我想把(Push_back)线程放在一个向量中,并在每次从向量执行弹出操作后启动线程。
#include <iostream>
#include <thread>
#include <algorithm>
int main() {
std::vector<std::thread> workers;
for(int i = 0; i < 10; ++i){
workers.push_back(std::thread([](){
std::cout << "Hi from thread\n";
}));
}
std::cout << "Hi from main!\n";
std::for_each(workers.begin(), workers.end(), [](std::thread &th){
th.join();
});
return 0;
}但是push_back()指令实际上并不表示我们正在存储线程,以便稍后启动它。因为调用class std::thread的构造函数会立即启动线程。
在java中,可以通过将线程放入队列(比如)并将其从队列中移出,来启动线程,如下所示:
-> searchQueue.enqueue( new SearchTask( record, this ) );
-> return searchQueue.size () > 0 ? (Runnable) searchQueue.removeFirst () : null ;因为在java中,线程是在你调用class Thread的start()方法之后启动的。
那么,如何在C++11中执行类似的操作呢?
发布于 2015-01-07 14:01:53
您可以存储未运行的线程以及它们稍后将一起运行的函数:
typedef std::pair<std::thread, std::function<void()>> ThreadAndFunction;
std::vector<ThreadAndFunction> workers;
for(int i = 0; i < 10; ++i){
ThreadAndFunction tf;
workers.emplace_back(std::thread(), [](){
std::cout << "Hi from thread\n";
});
}然后,使用以下函数激活线程:
for(int i = 0; i < 10; ++i){
workers[i].first = std::thread(workers[i].second);
}然而,我不认为你在这里收获很多。您可以只存储函数,而不存储空线程,然后创建一个线程向量。
https://stackoverflow.com/questions/27812913
复制相似问题