2

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 ?

3
  • Yes, that is possible. Commented Jul 15, 2015 at 5:26
  • @DrewDormann what do i need to store the parameter ? std::initializer_list or variadic arguments ? Commented Jul 15, 2015 at 5:32
  • 1
    Yes. Its called a thread pool. Its the first thing that anybody learning threads writes. Commented Jul 15, 2015 at 6:30

1 Answer 1

3

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();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

wow! i didn't know something about std::bind! big thanks for the work!
@Roby: The other thing commonly stored in std::function are lambda's: [param1, param2}() { func1(param1, param2); }. The advantage is that lambda's allow more complex code: [param1, param2}() { func1(param1, ) * func2(param2); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.