im trying to synchronize a producer consumer case as following (the small reproducible instance of my scenario)
#include<thread>
#include<condition_variable>
#include<deque>
class Multi_Thread_Test{
public:
std::mutex mu;
std::condition_variable cond;
std::deque<int>stored;
Multi_Thread_Test(){
}
void Producer(){
std::unique_lock<std::mutex>locker(mu);
srand(time(0));
stored.push_back(rand());
locker.unlock();
cond.notify_one();
}
void Producer_loop(){
while(true){
std::thread t1([&]{Producer();});
std::thread t2([&]{Producer();});
t1.join();
t2.join();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
void Consumer() {
std::thread pl([&]{this->Producer_loop();});
while (true) {
std::unique_lock<std::mutex> locker(mu);
cond.wait(locker, [&] { return !stored.empty(); });
int temp = stored.front();
stored.pop_front();
locker.unlock();
}
}
};
int main() {
Multi_Thread_Test test;
test.Consumer();
std::cin.get();
std::cin.get();
return 0;
}
the program compiles successfully but getting the following error when executing the program
Segmentation fault (core dumped)
Debug:SIGSEGV (signal SIGSEGV: invalid address (fault address: 0x0))
and when debugging it i found out that it occurs on cond.wait
and cond.notify_one
calls.
ive captured by reference in lambada thread spawns but it seems the condition_variable might not captured the correct way.
what is the cause of this error and how can i fix this or implement this logic in the correct way?