如何在 C++11 中调度线程
How to schedule a thread in C++11?
使用以下代码,我想将线程放在(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);
}
但是,我认为您在这里没有获得太多收益。 您可以一开始只存储没有空线程的函数,稍后再创建线程向量。
相关文章:
- 更改线程实时调度策略失败:config_rt_group_sched = y
- 从调度队列块 [ swift / c++ ] 创建线程
- 用管道在C++中创建调度队列/线程处理程序:FIFO溢出
- C 1Z Coroutine线程上下文和Coroutine调度
- 在多线程中调度任务
- 在进程中调度线程
- 调度线程时的 void* 指针转换
- 如何确定流程的"经理"和"工作线程"线程的优先级(或为其设置调度策略)?
- 如何在 C++11 中调度线程
- Android 的 c++11 多线程问题,其中某些线程未正确调度
- 在后台线程上创建的调度程序未关闭时会发生什么情况?如何确保调度程序已正确关闭
- 线程调度程序模拟:唤醒和睡眠Pthread的正确方法
- xiAPI:无法更改线程调度程序,请检查实时优先级的用户限制
- 大中央调度块线程安全吗?
- 调度基于Posix的线程
- 如何调度/创建用户级线程,以及如何创建内核级线程
- 在Qt应用程序中自定义线程调度
- 调度大量线程,因此只有4个线程并行执行
- 如何在 boost::wait_for_any 中正确调度任务,同时考虑到线程数
- 如何使用boost::asio::io_service在c++ 11线程之间调度作业