First, let me introduce you to my problem.
My code looks like this:
#include <iostream> #include <thread> #include <condition_variable> std::mutex mtx; std::mutex cvMtx; std::mutex mtx2; bool ready{false}; std::condition_variable cv; int threadsFinishedCurrentLevel{0}; void tfunc() { for(int i = 0; i < 5; i++) { //do something for (int j = 0; j < 10000; j++) { std::cout << j << std::endl; } //this is i-th level mtx2.lock(); threadsFinishedCurrentLevel++; if (threadsFinishedCurrentLevel == 2) { //this is last thread in current level threadsFinishedCurrentLevel = 0; cvMtx.unlock(); } mtx2.unlock(); { //wait for notify unique_lock<mutex> lck(mtx); while (!ready) cv_.wait(lck); } } } int main() { cvMtx.lock(); //init std::thread t1(tfunc); std::thread t2(tfunc); for (int i = 0; i < 5; i++) { cvMtx.lock(); { unique_lock<mutex> lck(mtx); ready = true; cv.notify_all(); } } t1.join(); t2.join(); return 0; } I have 2 threads. My computation consists of levels(for this example, lets say we have 5 levels). On the same level, computation can be divided to threads. Each thread then calculates part of a problem. When i want to step to the next(higher) level, lower level must be first done. So my idea is something like this. When last thread on the current level is done, it unlocks main thread, so it can notify all of the threads to continue to next level. But this notify has to be called more then once. Because there are plenty of these levels. Can this condition_variable be restarted or something? Or do I need for each level one condition_variable? So for example, when i have 1000 levels, i need to allocate dynamically 1000x condition_variable?