public member function
<mutex>

std::unique_lock::operator bool

explicit operator bool() const noexcept;
返回是否擁有鎖
返回物件是否*擁有鎖*。

如果管理的*互斥量物件*已被*採用*(即被鎖定),並且自此未被*解鎖*或*釋放*,則此值為true

在所有其他情況下,此值為false

這是unique_lock::owns_lock的別名。

引數



返回值

如果物件擁有對所管理*互斥量物件*的鎖,則為true
否則返回 false

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// unique_lock::operator= example
#include <iostream>       // std::cout
#include <vector>         // std::vector
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lock, std::try_to_lock

std::mutex mtx;           // mutex for critical section

void print_star () {
  std::unique_lock<std::mutex> lck(mtx,std::try_to_lock);
  // print '*' if successfully locked, 'x' otherwise: 
  if (lck)
    std::cout << '*';
  else                    
    std::cout << 'x';
}

int main ()
{
  std::vector<std::thread> threads;
  for (int i=0; i<500; ++i)
    threads.emplace_back(print_star);

  for (auto& x: threads) x.join();

  return 0;
}

可能的輸出('x' 的數量 - 如果有的話 - 可能有所不同)

***********************************x*****x******************x*******************
****************x**x*x*x***x***x************************x**************x********
********************************************************************************
********************************************************************************
****************************************************************x***************
***x****************************************************************************
******x**********x**


資料競爭

訪問 unique_lock 物件。
其管理的*互斥量物件*未被該操作訪問。

異常安全

無異常保證: 絕不丟擲異常。

另見