几个线程的多个任务
multiple tasks for a few threads
我正在使用 c++11 上的线程库来做一些事情。问题是我的线程数量有限 (4)。
我会知道如何处理它:
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#define NUMBER_OF_THREADS 4
void foo(const std::string& astring)
{
std::cout << astring << std::endl;
}
int main()
{
std::vector<std::string> list_of_strings(100);
// values assigned
std::vector<std::thread> list_of_threads(NUMBER_OF_THREADS);
for(std::vector<std::string>::const_iterator it_string = list_of_strings.begin() ; it_string != list_of_strings.end() ; ++it_string)
{
bool check = false;
unsigned int = 0;
while(!check) // loop which assigns the next task to the first thread ready.
{
if( check = list_of_threads.at(i).ISFREE()) // how to do ?
{
list_of_threads.at(i) = thread(&foo,*it_string);
}
else
{
i = (i + 1) % NUMBER_OF_THREADS;
}
}
}
for(std::vector<std::thread>::iterator it = list_of_threads.begin() ; it != list_of_threads.end() ; ++it)
it->join(); // the main thread is waiting for all threads before closing.
return 0;
}
但是我不知道如何检查线程是否已准备好执行新任务。知道吗?
通常的解决方案是将任务存储在共享队列中(受互斥锁和条件变量保护),并让每个线程在完成当前任务时检查其他任务。 这样,每个线程都保持忙碌,程序的其余部分可以幸福地忽略分配。
没有好的内置方式。您可以使用 std::async
而不是 std::thread
返回您可以查询的std::future
- 这在一般情况下可能更可取,因为它完全按照您正在做的事情 - 处理工作项而不会启动操作系统线程的全部开销。
或者,你可以让你的线程发出它完成的信号(比如通过std::atomic
或更可能的std::condition_variable
),然后从主线程.join()
它以确保它真正终止。
我不熟悉 std::thread,但假设没有更好的线程类具有您需要的功能(也许参见 Mikes 的回答),我建议基于 std::thread 编写自己的线程类。 std::thread将获得一个指向您自己的成员函数的函数指针,该函数设置线程繁忙的内部标志, 然后调用从外部提供的函数,然后重置所述标志。添加一个返回标志状态的方法IsBusy()
,你就完成了。
相关文章:
- 如何创建线程序列以按照启动顺序执行任务?
- C++一个线程如何正确通信其任务已完成?
- 对于同一任务,线程的等待时间在 0 到 30000 微秒之间系统地切换
- 在iOS设备上执行并发任务时如何设置正确的线程数?
- 如何从父线程中提取 pthread 的任务 id(tid)
- 根据硬件并发性将任务平均划分为线程
- C++生产者使用者中,同一使用者线程会抓取所有任务
- 正在执行 omp 任务的线程数
- 您可以在 OpenMP 中将特定线程 ID 分组到唯一的任务组中吗?
- 是boost :: asio :: thread_pool线程在多个线程上发布任务时的安全性
- asio::strand 上的任务在单个线程上运行
- 如何在C++中创建高效的多线程任务计划程序
- 如何在多个线程上正确分发任务
- 在多线程中调度任务
- Poco任务管理器/Boost线程混合和匹配
- 将执行从一个线程移动到另一个线程,以实现任务并行性并在将来调用
- 使用C 多任务.线程或不同的设计
- 如何处理任务,同时剩余的线程完成工作
- 多线程任务总体进度报告的设计模式
- 在OpenMP中屈服于其他线程/任务