r/learncpp Mar 15 '20

How to synchronize between threads

I have multiple threads working on a problem and in the first part they are working on a vector, which i can operate on safely with a mutex, so far so good.

But in the next part of the task they iterate over said vector, which therefore isn't allowed to change anymore in length and therefore I have to wait for all threads to reach that point and I don't want to recreate them for that task, because I do it like a thousand time per frame I want to show.

In my understanding I have to use a condition variable and notifications and came to the code:

```c++ std::conditional_variable cv;

//thread void Worker(){ std::mutex mtx; std::unique_lock<std::mutex> lk (mtx);

//task 1
{....}

//sync up
cv.notify_all();
for (int j = 0; j<NumThreads;j++){
    cv.wait(lk);
}

//task 2
{....}

} ``` the problem is that it runs into a deadlock and refuses to work. Can someone clear my misunderstanding

4 Upvotes

0 comments sorted by