Reputation: 2061
is it possible to create N std::thread objects, each running a while loop until the "task" list is not empty ?
It could be look like this:
Schedule sched( N );
schned.add( func1, param1, param2, param3 );
schned.add( func1, param1, param2, param3 );
schned.add( func2, param1 );
schned.add( func3, IntegerParam );
schned.add( func4, StringParam );
sched.start(); // start & join each thread wait until all threads finished
with function declaration:
bool func1( int, int, int );
bool func2( int );
bool func3( int );
bool func4( std::string );
is this possible with variadic arguments ?
Upvotes: 2
Views: 174
Reputation: 30494
This should be pretty simple with std::bind
and std::function
so long as all of the functions have the same return type.
In your Schedule
class you can just store a std::queue<std::function<bool()>>
. Then have Schedule::add()
look something like this:
template<typename func>
Schedule::add(func f) {
// Appropriate synchronization goes here...
function_queue.push_front(f); // Will work as long as func can be converted to std::function<bool()>
}
Then you can add tasks like so:
Shedule sched(N);
// This works with function pointers
sched.add(someFunctionThatTakesNoArgs);
// And function like objects such as those returned by std::bind
sched.add(std::bind(func1, param1, param2, param3));
sched.add(std::bind(func1, param1, param2, param3));
sched.add(std::bind(func2, param1));
// Even member functions
SomeClass foo;
sched.add(std::bind(SomeClass::func3, foo, IntegerParam));
sched.add(std::bind(SomeClass::func4, foo, StringParam));
sched.start();
Then just have your worker threads do something like:
Schedule::worker() {
// Synchronization left as an exercise for the reader...
while (more_work_to_do) {
std::function<bool()> f(function_queue.pop_back());
f();
}
}
Upvotes: 3