Alfred
Alfred

Reputation: 307

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 ?

Upvotes: 3

Views: 2500

Answers (3)

SvenS
SvenS

Reputation: 795

I'm not familiar with std::thread, but assuming there is no better thread class available that has the functionality you need (see Mikes answer perhaps), I would propose writing your own thread class based on std::thread. std::thread would get a function pointer to your own member function, that sets an internal flag that the thread is busy, then calls the function that was provided from outside, then resets said flag. Add a method IsBusy() that returns the state of the flag, and you're done.

Upvotes: 0

Drew Hall
Drew Hall

Reputation: 29047

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.

Upvotes: 5

Mike Vine
Mike Vine

Reputation: 9837

There's no good built in way. You can either use std::async instead of std::thread which returns a std::future which you can query - this is probably preferable in the general case as it does exactly what you are doing - process work items without the whole overhead of spinning up an OS thread.

Alternatively you can get your thread to signal that its done (say via std::atomic or more likely std::condition_variable) and then .join() it from the main thread to ensure its truly terminated.

Upvotes: 3

Related Questions