gpt4 book ai didi

c++ - 如何在 C++11 中调度线程?

转载 作者:行者123 更新时间:2023-11-28 02:34:56 24 4
gpt4 key购买 nike

使用下面的代码,我想将线程放置(push_back)在一个 vector 中,并在 vector 中的每个弹出操作之后启动线程。

#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 Threadstart() 方法后启动。

那么,我如何在 C++11 中执行类似的操作?

最佳答案

您可以存储非运行线程以及它们稍后将一起运行的函数:

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);
}

但是,我认为您在这里收获不大。您可以先存储没有空线程的函数,然后再创建一个线程 vector 。

关于c++ - 如何在 C++11 中调度线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27812913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com