I have mailBox class with send and receive methods shared between threads, and threads: thread1 send message, threads 2 and 3 receive messages, how I must using mutex for synchronize this?
Any combinations that I have tried hasn't led to success.
std::mutex g_lock; //in global
void sendMessage(Message msg) {
if (g_lock.try_lock()) {
this_thread::sleep_for(100ms); // DELAY
messages->push_back(msg);
g_lock.unlock();
}
}
The same for Receive method
full code: https://pastebin.com/7y2RC5br
Also this code can't be debugged because delays change the logic of the code.
Correct logic of the code: thread2/3 try lock and read msg, get empty then unlock thread1 try lock and send msg then unlock thread2/3 try lock and read msg, get msg and write to file then unlock
When I have tried mutex's try_lock from threads 2/3, I had been getting constantly blocked thread and thread 1 was had been working after ALL threads 2/3.