In case I'm using a cv without a predicate. I don't quite understand the use of the unique_lock that we pass in. I checked this link: Why does a condition variable need a lock (and therefore also a mutex) and more links from that.
Most of the explanations suggested that the mutex was used to get a lock on the predicate that was being passed into the CV. So, in case I don't use a predicate function, why is the lock required?
A hypothetical code without a lock could look something this:
condition_variable cv;
mutex dataMutex;
string sharedData;
atomic<bool> flag = false;
void doTask(){
while(!flagSet){ // To prevent spurious wake-up
cv.wait(); //Just wait, no lock/predicate passed in.
}
lock_guard<mutex> lock(dataMutex); //Get a lock and read shared data
cout << sharedData;
}
void createTask(){
lock_guard<mutex> lock(dataMutex); //Get a lock and update the shared data
sharedData = "abc";
flag = true;
cv.notify_all();
}
int main(){
thread a(doTask, 10);
sleep(seconds(5));
thread b = thread(createTask);
// Join the threads and return.
}
Possibly the cv could internally use a mutex to synchronize the wait and notify, but why does it need an external one. Could anyone please help understand the use of an external lock when I don't have a predicate?