几个线程的多个任务

时间:2013-09-30 12:10:17

标签: c++ multithreading c++11

我正在使用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;
}

但我不知道如何检查线程是否已准备好执行新任务。有什么想法吗?

3 个答案:

答案 0 :(得分:5)

通常的解决方案是将任务存储在共享队列中(由互斥锁和条件变量保护),并让每个线程在完成当前任务时检查其他任务。这样每个线程都会保持忙碌,程序的其余部分仍然可以无视分配。

答案 1 :(得分:3)

没有好的内置方式。您可以使用std::async代替std::thread,它会返回您可以查询的std::future - 这在一般情况下可能更可取,因为它完全正如您所做的那样 - 处理工作项而不使用启动OS线程的全部开销。

或者你可以让你的线程发出信号表明它已经完成(比如通过std::atomic或更可能是std::condition_variable),然后从主线程发出.join()来确保它真正终止。< / p>

答案 2 :(得分:0)

我不熟悉std :: thread,但假设没有更好的线程类可用,你需要的功能(也许参见Mikes的回答),我建议你根据std :: thread编写自己的线程类。 std :: thread会得到一个指向你自己的成员函数的函数指针,它设置一个线程忙的内部标志,然后调用从外部提供的函数,然后重置所述标志。添加一个返回标志状态的方法IsBusy(),然后就完成了。

相关问题