几个线程的多个任务

Alf*_*red 2 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;
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何检查线程是否已准备好执行新任务.任何的想法 ?

Dre*_*all 5

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