Concurrency waiting problem

I have a very simple code below that I'm using for testing purposes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <vector>
#include <thread>

using namespace std;

condition_variable CONDITIONVAR;
mutex MUTEXVAR;

void first() {
   MUTEXVAR.lock();
   CONDITIONVAR.notify_all();
}

void second() {
   unique_lock<mutex> SOMELOCK(MUTEXVAR);
   CONDITIONVAR.wait(SOMELOCK);
}

int main(void) {
  vector<thread> threadvec;
  threadvec.push_back(thread(first));
  threadvec.push_back(thread(second));
    
  for (int i = 0; i < threadvec.size(); i++)
    threadvec[i].join();

  return 0;
}


The problem is that the program gets stuck and never finishes the wait procedure in second(). There's only one lock ever performed on the mutex variable, so I don't see why the wait procedure would go on forever. How can I solve this problem?
I see that function first locks the mutex, and doesn't unlock it.

It looks like function second then tries to lock that mutex, and will block forever because it sits there waiting forever for the mutex to become available for locking.
Last edited on
It seems to me that notify_all() only notifies waiting threads. This is a problem for my serious application. I have threads which sleep for varying amounts of time before resuming execution. If the notifications happen before the wait procedures are called, it will get stuck forever just like in this case. What is a working solution to this problem?
it will get stuck forever just like in this case


In this case, the thread running second get stuck because you lock a mutex and never unlock it. Nothing to do with notifying. If you fix that, then your code will block waiting for a notification that already happened.

If the notifications happen before the wait procedures are called, it will get stuck forever just like in this case. What is a working solution to this problem?

Write your code such that threads don't wait for notifications that will never happen. There's no magic to it. You're just writing code full of deadlocks and waiting forever. Don't do that.
Last edited on
Topic archived. No new replies allowed.