2

私はいくつかのことをするために 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;
}

しかし、スレッドが新しいタスクの準備ができているかどうかを確認する方法がわかりません。何か案が ?

4

3 に答える 3