extend threads life

I have a program which creates some threads which perform in parallel operations over different memory areas. The main needs to wait for them to finish to perform some crossing operation between those areas, then the threads should start again repeating the same operations they did before. This for something like a million times.

I implemented this with create and join threads. But as the thread creation process is pretty long I would like to keep threads alive but sleeping and waiting for a signal from the main to proceed, then sleep again while the main updates the data.

I am pretty confused about how implementing this.. condition variables? futures? I am looking for the simplest and fastest solution.

Thank you!
Condition variable + mutex + bool flags or an int counter is the standard low-level tool for this kind of signaling. Sounds like you'll need two: have main wait on a cv after it launched the workers. Have the worker threads notify the cv when ready and immediately wait on a second cv before looping back to work. Have main notify that second cv when it's done the "crossing operation", and loop back to wait on the first cv.

If profiling shows that the time to wake each thread after the notify is significant, you can replace the cv waits with spinlocks (which can be implemented lock-free, although it's not important in this case), but first get the basic design working.
This is basically what I was thinking but the implementation is not obvious to me, I always end up in a deadlock.

Threads (c++11 style) are constructed with a function and the pointer to the correct memory area.

I have many doubts: can I share the same cv between multiple threads? Should I use multiple flags? How, if the function is the same?
can I share the same cv between multiple threads?

Yes; that's why "notify_all()" exists

Should I use multiple flags?

a bool flag per thread or an int counter. or, as rightfully pointed out at SO ( http://stackoverflow.com/questions/15252292/extend-the-life-of-threads-with-synchronization-c11 ) ,at that point you'd be reimplementing boost::barrier (which is actually difficult in general case)

How, if the function is the same?

they are called with different arguments (you can always pass more than just that pointer) and they have different thread ids.
Topic archived. No new replies allowed.