某日二师兄参加XXX科技公司的C++工程师开发岗位第31面:

#include <pthread.h>
pthread_mutex_t mutex_ = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex_);
//被保护的区域
pthread_mutex_unlock(&mutex_);
#include <mutex>
std::mutex mutex_;
mutex_.lock();
//被保护的区域
mutex_.unlock();
class lock_guard
{
    explicit lock_guard(std::mutex& m):mutex_(m)
    {
        mutex_.lock();
    }
    ~lock_guard()
    {
        mutex_unlock();
    }
private:
    std::mutex& mutex_;
};

让我们来看看最后一个问题:

adopt_lock_t/defer_lock_t/try_to_lock_t都是空类,主要表示std::lock_guradstd::unqiue_lock的默认构造中的操作:

adopt_lock_t:默认互斥量已被当前线程锁定,不使用lock()方法对互斥量加锁:

std::mutex mtx_;
mtx_.lock();	//lock
{
    std::lock_guard<std::mutex> lock_(mtx_,std::adopt_lock);	//这里默认当前线程已经对mtx_加过锁
    ...
}//unlock

defer_lock_t:虽然我拥有了std::mutex的引用,但是在构造函数中并不调用lock()方法对互斥量加锁:

std::mutex mtx_;
{
    std::unique_lock<std::mutex> ulock_(mtx_,std::defer_lock);	//这里并没有加锁
    ulock_.lock();
    if(ulock_.owns_lock())
    {
		//locked
    }else
    {
		//unlocked
    }
}//if locked,unlock

try_to_lock_t:在构造函数执行是并不是使用lock()方法加锁,而是使用try_lock()方法加锁:

std::mutex mtx_;
{
    std::unique_lock<std::mutex> ulock_(mtx_,std::try_to_lock);	//这里mtx_如果没有被锁定,则加锁成功,否则加锁失败
    if(ulock_.owns_lock())
    {
		//locked
    }else
    {
		//unlocked
    }
}//if locked,unlock

adopt_lock_t可以用于std::lock_guradstd::unique_lock,而defer_lock_t/try_to_lock_t只能用于std::unique_lock

07-05 06:00