为什么unique_lock在没有互斥锁时会调用解锁?

时间:2016-07-23 14:26:14

标签: c++ multithreading c++11 stl locking

在此示例中,使用标志std :: defer_lock调用std :: unique_lock。在cppreference上写道:" defer_lock_t不获取互斥锁的所有权" 和:"(析构函数)解锁相关的互斥锁,如果拥有"

现在,这个问题!

为什么在这个例子中,std :: unique_lock在析构函数中调用解锁?

void transfer(Box &from, Box &to, int num)
{
    // don't actually take the locks yet
    std::unique_lock<std::mutex> lock1(from.m, std::defer_lock);
    std::unique_lock<std::mutex> lock2(to.m, std::defer_lock);

    // lock both unique_locks without deadlock
    std::lock(lock1, lock2);

    from.num_things -= num;
    to.num_things += num;

    // 'from.m' and 'to.m' mutexes unlocked in 'unique_lock' dtors
}

···

1 个答案:

答案 0 :(得分:3)

因为std::defer_lock用来表示“我稍后会以某种方式获取锁定”,这是对std::lock(lock1, lock2)的调用。因此,锁在析构函数中调用unlock。要对此进行测试,您可以尝试直接向std::lock std::lock(from.m, to.m);提供互斥锁:unique_lock。如果这样做,std::adopt_lock将无法解锁互斥锁,因为他们不拥有互斥锁。

还有std::defer_lock,上面写着“我已经拥有锁”。

这两种方法大致相同,但您不能将std::lock_guardlock一起使用,因为它没有// Intent for the activity to open when user selects the notification Intent detailsIntent = new Intent(this, DetailsActivity.class); // Use TaskStackBuilder to build the back stack and get the PendingIntent PendingIntent pendingIntent = TaskStackBuilder.create(this) // add all of DetailsActivity's parents to the stack, // followed by DetailsActivity itself .addNextIntentWithParentStack(upIntent) .addNextIntent(detailsIntent); .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentIntent(pendingIntent); 方法。