I started just recently learning about multithreading and in I looked up the concept of condition variable. I tried a small example to get a feeling of how it works. I read this stackoverflow post which helped me a bit but everything is not yet clear.
#include <iostream>
#include <mutex>
using namespace std;
bool g_ready = false;
mutex g_mutex;
condition_variable g_cv;
void senderThread()
{
g_mutex.lock();
g_ready = true;
g_cv.notify_one();
g_mutex.unlock();
}
void receiverThread()
{
unique_lock<mutex> ul(g_mutex);
g_cv.wait(ul, []() {return g_ready; });
cout << "execute receiver task" << endl;
}
int main()
{
thread t1(senderThread);
thread t2(receiverThread);
t1.join();
t2.join();
return 0;
}
Question : there are some things I didn't grasp. As I understand it, wait() needs as an argument the unique lock because if the condition is not fulfilled, it needs to release the mutex. However
- Why is the unlock called inside the wait function?
- Is there a reason why we cannot just pass the mutex as an argument to wait() and we need the unique_lock format?
- What would the pseudocode of wait() look like?
added
this post addresses the second point/question. If I understand it correctly, it says that
void foo()
{
unique_lock<mutex> lk(mut);
// mut locked by this thread here
while (not_ready)
cv.wait(mut);
// mut locked by this thread here
}
wouldn't allow to call lk.owns_lock()
from within the wait()
function, but why exacltly is it needed?