如何在 C++11 中调度线程

How to schedule a thread in C++11?

本文关键字:调度 线程 C++11      更新时间:2023-10-16

使用以下代码,我想将线程放在(push_back)向量中,并在每次从 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 threadn";
            }));
    }
    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中,线程的启动可以通过放入Queue(比如)并像这样取消排队来实现:

-> searchQueue.enqueue( new SearchTask( record, this ) );
-> return searchQueue.size () > 0 ? (Runnable) searchQueue.removeFirst () : null ;

因为在 java 中,线程在您调用start() class Thread方法后启动。

那么,如何在 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 threadn";
        });
}

稍后,使用以下函数激活线程:

for(int i = 0; i < 10; ++i){
    workers[i].first = std::thread(workers[i].second);
}

但是,我认为您在这里没有获得太多收益。 您可以一开始只存储没有空线程的函数,稍后再创建线程向量。