I have a program, which I distilled into this short MRE:
#include <mutex>
#include <condition_variable>
#include <thread>
#include <unistd.h>
std::mutex mu;
std::condition_variable cv;
void test(){
std::unique_lock lk(mu);
cv.wait(lk);
}
int main(){
std::thread(test).detach();
sleep(3);
}
If you run it, you will note that it hangs, even accounting for the 3s sleep. If you run the program under gdb, and interrupt it while it's hanging, you will see that it is blocked at pthread_cond_destroy
. If you look at the backtrace at this point, you will see that it is due to cv
's destructor.
I'm not completely sure why it happens.
Thanks to a comment by Caleth, I was able to find a solution:
class wrapper {
std::mutex mutex;
std::condition_variable cond_var;
public:
std::atomic<bool> abool=false;
void not(){
cond_var.notify_all();
}
void wait(){
std::unique_lock lk(mutex);
cond_var.wait(lk);
}
~wrapper(){
abool=true;
not();
}
};
After the condition variable unlocks, I just check whether abool
is set to true --- if so, I exit.