几个线程的多个任务

multiple tasks for a few threads

本文关键字:线程 任务 几个      更新时间:2023-10-16

我正在使用 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(),你就完成了。