c++11的mutex unique_lock和lock_guard区别

 C++11中有一个区域锁lock_guard,还有第二个区域锁unique_lock

    区域锁lock_guard使用起来比较简单,除了构造函数外没有其他member function,在整个区域都有效。

    区域锁unique_guard除了lock_guard的功能外,提供了更多的member_function,相对来说更灵活一些。

    unique_guard的最有用的一组函数为:

   

locks the associated mutex 
(public member function)
tries to lock the associated mutex, returns if the mutex is not available 
(public member function)
attempts to lock the associated TimedLockable mutex, returns if the mutex has been unavailable for the specified time duration 
(public member function)
tries to lock the associated TimedLockable mutex, returns if the mutex has been unavailable until specified time point has been reached 
(public member function)
unlocks the associated mutex 

    通过上面的函数,可以通过lock/unlock可以比较灵活的控制锁的范围,减小锁的粒度。

    通过try_lock_for/try_lock_until则可以控制加锁的等待时间,此时这种锁为乐观锁。

    以上为粗浅理解,后面有新的心得在补充之。

阅读更多

c++ mutex, unique_lock, lock_guard官方例程 , std::lock_guard lk(m) 似乎可有无

12-30

最下面是c++ 官方程序rnhttp://en.cppreference.com/w/cpp/thread/condition_variablern1. rn rn[color=#FF00FF] std::lock_guard lk(m);[/color]rn ready = true;rn std::cout << "main() signals data ready for processing\n";rn rn红色的部分似乎没有起任何作用,删掉没有任何影响,都是顺序执行下来,ready=true之后, cv.notifyone(), 然后worker_thread 就可以继续执行。为什么要加这个红色的部分。rnrn2. 程序中三次使用mutexrnstd::mutex m;rnstd::unique_lock lk(m);rnstd::lock_guard lk(m);rnstd::unique_lock lk(m);rn三次锁的都是同一个m,这里有必要锁同一个m吗,如果下面这样可以吗rnstd::mutex m;rnstd::mutex m1;rnstd::mutex m2;rnstd::unique_lock lk(m);rnstd::lock_guard lk(m1);rnstd::unique_lock lk(m2);rnrnrnrn[code=c]#include rn#include rn#include rn#include rn#include rn rnstd::mutex m;rnstd::condition_variable cv;rnstd::string data;rnbool ready = false;rnbool processed = false;rn rnvoid worker_thread()rnrn // Wait until main() sends datarn std::unique_lock lk(m);rn cv.wait(lk, []return ready;);rn rn // after the wait, we own the lock.rn std::cout << "Worker thread is processing data\n";rn data += " after processing";rn rn // Send data back to main()rn processed = true;rn std::cout << "Worker thread signals data processing completed\n";rn rn // Manual unlocking is done before notifying, to avoid waking uprn // the waiting thread only to block again (see notify_one for details)rn lk.unlock();rn cv.notify_one();rnrn rnint main()rnrn std::thread worker(worker_thread);rn rn data = "Example data";rn // send data to the worker threadrn rn std::lock_guard lk(m);rn ready = true;rn std::cout << "main() signals data ready for processing\n";rn rn cv.notify_one();rn rn // wait for the workerrn rn std::unique_lock lk(m);rn cv.wait(lk, []return processed;);rn rn std::cout << "Back in main(), data = " << data << '\n';rn rn worker.join();rn[/code]rnrn

没有更多推荐了,返回首页