繁体   English   中英

如何在C ++ 11中安排线程?

[英]How to schedule a thread in C++11?

使用下面的代码,我想将线程放置(推回)向量中,并在每次从向量执行弹出操作后启动线程。

#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中,可以通过将Queue(say)放入队列并使其出队来启动线程:

-> searchQueue.enqueue( new SearchTask( record, this ) );

-> return searchQueue.size () > 0 ? (Runnable) searchQueue.removeFirst () : null ;

因为在Java中,线程是在调用class Thread start()方法后start()

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

但是,我认为您在这里没有收获太多。 您可以先存储没有空线程的函数,然后再创建线程向量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM