i am looking at this piece of code:
#include <chrono> #include <iostream> #include <map> #include <mutex> #include <shared_mutex> #include <string> #include <thread> bool flag; std::mutex m; void wait_for_flag() { // std::cout << &m << std::endl; // return; std::unique_lock<std::mutex> lk(m); while (!flag) { lk.unlock(); std::cout << "unlocked....." << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(100)); std::cout << "sleeping....." << std::endl; lk.lock(); std::cout << "locked by " << std::this_thread::get_id() << "....." << std::endl; } } int main(int argc, char const *argv[]) { std::thread t(wait_for_flag); std::thread t2(wait_for_flag); std::thread t3(wait_for_flag); std::thread t4(wait_for_flag); std::thread t5(wait_for_flag); t.join(); t2.join(); t3.join(); t4.join(); t5.join(); return 0; } I am new to this, and I thought mutex can only be acquired by one thread. I got two questions:
- why there is no deadlock among those threads, e.g. if thread A runs lk.unlock(), then thread B runs lk.lock() and then thread A runs lk.lock().
- what does it mean we define a new unique_lock in every thread associating to the same mutex lock (which is called m in here)
Thanks
lk.unlock();this unlocks the mutex as soon as you have locked it. Seems pointless.lockandunlockon the mutex, the same as you could do manually without the lock (but then you run in trouble when there is an exception). Basically what I wrote in the answer