-sharpinclude <iostream>
-sharpinclude <queue>
-sharpinclude <thread>
-sharpinclude <mutex>
-sharpinclude <condition_variable>
using namespace std;
mutex mtx;
condition_variable produce, consume;
queue<int> q;
int maxSize = 20;
void consumer() {
while (true) {
//
unique_lock<mutex> lck(mtx);
cout << "hello\n";
consume.wait(lck, []{return q.size() != 0; });
cout << "consumer " << this_thread::get_id() << ": ";
q.pop();
cout << q.size() << "\n";
produce.notify_all();
}
}
void producer(int id) {
while (true) {
this_thread::sleep_for(chrono::seconds(10));
unique_lock<mutex> lck(mtx);
cout << "hi\n";
produce.wait(lck, [] { return q.size() != maxSize; });
cout << "-> producer " << this_thread::get_id() << ": ";
q.push(id);
cout << q.size() << "\n";
consume.notify_all();
}
}
int main() {
thread con(consumer);
thread pro(producer, 1);
con.join();
pro.join();
return 0;
}
excuse me, both the consumer and the producer are locking the same lock in the code. Why can the producer still get the lock after the consumer gets the lock first? Why aren"t producers blocking unique_lock < mutex > lck (mtx)
?
the running result of the program is shown above