Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple tasks for a few threads

I'm using the thread library on c++11 to do some things. The problem is that i have a limited number of threads (4).

I would know how to deal with it:

#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;
}

But i don't know how to check if the thread is ready for a new task or not. Any idea ?

like image 836
Alfred Avatar asked Dec 28 '25 07:12

Alfred


1 Answers

The usual solution is to store the tasks in a shared queue (protected by a mutex and a condition variable) and have each thread check for additional tasks when it completes the current one. This way each thread stays busy and the rest of the program can remain blissfully ignorant of the allocation.

like image 128
Drew Hall Avatar answered Dec 30 '25 20:12

Drew Hall