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.
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?
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.