整理转自:https://github.com/forhappy/Cplusplus-Concurrency-In-Practice/tree/master/zh/chapter4-Mutex
Table of Contents
1.4 std::recursive_timed_mutex 类摘要
2.4 std::recursive_timed_mutex 介绍
3.2.2 std::unique_lock 移动(move assign)赋值操作
0. 简述
C++11 中定义了如下与互斥量和锁相关的类:
-
Mutex 系列类(四种),C++11 标准中规定的与互斥量相关的类包括:
std::mutex
,最基本的 Mutex 类,该类提供了最基本的上锁和解锁操作。同时,基本的互斥量不允许某个线程在已获得互斥量的情况下重复对该互斥量进行上锁操作,所以重复上锁将会导致死锁(结果通常未定义的)。std::recursive_mutex
,递归 Mutex 类,与std::mutex
功能基本相同,但是允许互斥量的拥有者(通常是某个线程)重复对该互斥量进行上锁操作而不会产生死锁,但必须保证上锁和解锁的次数相同。std::time_mutex
,定时 Mutex 类,与std::mutex
功能基本相同,但是提供了两个额外的定时上锁操作,try_lock_for
和try_lock_until
,即某个线程在规定的时间内对互斥量进行上锁操作,如果在规定的时间内获得了锁则返回true
, 超时则返回false
,在本章后面的内容中我会介绍try_lock_for
和try_lock_until
两个上锁函数之间细微的差异。std::recursive_timed_mutex
,定时递归 Mutex 类,既提供了重复上锁功能,又提供了定时上锁的特性(即在规定的时间内没有获得锁则返回false
),相当于std::recursive_mutex
和std::time_mutex
的组合。
-
Lock 类(两种),C++11 标准中定义了两种与互斥量相关的 RAII 技术。(RAII:Resource Acquisition Is Initialization,资源获取即初始化,参见维基百科中与 RAII 相关的定义)C++17引入了std::scoped_lock,用以替代std::lock_guard。
std::lock_guard
,与 Mutex RAII 相关,方便线程对互斥量上锁。std::unique_lock
,与 Mutex RAII 相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。- std::scoped_lock,与 Mutex RAII 相关,方便线程对多个互斥量上锁,提供避免死锁的有效机制(since C++17)。
-
其他类型
std::once_flag
,call_once
辅助函数会使用到该类型的对象。std::adopt_lock_t
,一个空的标记类,定义如下:struct adopt_lock_t {};
,该类型的常量对象adopt_lock
(adopt_lock
是一个常量对象,定义如下:constexpr adopt_lock_t adopt_lock {};
,constexpr
是 C++11 中的新关键字) 通常作为参数传入给unique_lock
或lock_guard
的构造函数。std::defer_lock_t
,一个空的标记类,定义如下:struct defer_lock_t {};
,该类型的常量对象defer_lock
(defer_lock
是一个常量对象,定义如下:constexpr defer_lock_t defer_lock {};
) 通常作为参数传入给unique_lock
或lock_guard
的构造函数。。std::try_to_lock_t
,一个空的标记类,定义如下:struct try_to_lock_t {};
,该类型的常量对象try_to_lock
(try_to_lock
是一个常量对象,定义如下:constexpr try_to_lock_t try_to_lock {};
) 通常作为参数传入给unique_lock
或lock_guard
的构造函数。。
-
辅助函数
std::try_lock
,尝试同时对多个互斥量上锁。std::lock
,同时对多个互斥量上锁。std::call_once
,如果多个线程需要同时调用某个函数,call_once
可以保证多个线程对该函数只调用一次。
1.<mutex>
头文件摘要
<mutex>
头文件摘要如下:
<mutex> 头文件摘要如下:
namespace std {
class mutex;
class recursive_mutex;
class timed_mutex;
class recursive_timed_mutex;
struct defer_lock_t { };
struct try_to_lock_t { };
struct adopt_lock_t { };
constexpr defer_lock_t defer_lock { };
constexpr try_to_lock_t try_to_lock { };
constexpr adopt_lock_t adopt_lock { };
template <class Mutex> class lock_guard;
template <class Mutex> class unique_lock;
template <class Mutex>
void swap(unique_lock<Mutex>& x, unique_lock<Mutex>& y);
template <class L1, class L2, class... L3> int try_lock(L1&, L2&, L3&...);
template <class L1, class L2, class... L3> void lock(L1&, L2&, L3&...);
struct once_flag {
constexpr once_flag() noexcept;
once_flag(const once_flag&) = delete;
once_flag& operator=(const once_flag&) = delete;
};
template<class Callable, class ...Args>
void call_once(once_flag& flag, Callable func, Args&&... args);
}
1.1 std::mutex
类摘要
namespace std {
class mutex {
public:
constexpr mutex();
~mutex();
mutex(const mutex&) = delete;
mutex& operator=(const mutex&) = delete;
void lock();
bool try_lock() noexcept;
void unlock() noexcept;
typedef implementation-defined native_handle_type;
native_handle_type native_handle();
};
}
1.2 std::recursive_mutex
类摘要
namespace std {
class recursive_mutex {
public:
recursive_mutex();
~recursive_mutex();
recursive_mutex(const recursive_mutex&) = delete;
recursive_mutex& operator=(const recursive_mutex&) = delete;
void lock();
bool try_lock() noexcept;
void unlock() noexcept;
typedef implementation-defined native_handle_type;
native_handle_type native_handle();
};
}
1.3 std::timed_mutex
类摘要
namespace std {
class timed_mutex {
public:
timed_mutex();
~timed_mutex();
timed_mutex(const timed_mutex&) = delete;
timed_mutex& operator=(const timed_mutex&) = delete;
void lock();
bool try_lock();
template <class Rep, class Period>
bool try_lock_for(const chrono::duration<Rep, Period>& rel_time) noexcept;
template <class Clock, class Duration>
bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time) noexcept;
void unlock();
typedef implementation-defined native_handle_type;
native_handle_type native_handle();
};
}
1.4 std::recursive_timed_mutex
类摘要
namespace std {
class recursive_timed_mutex {
public:
recursive_timed_mutex();
~recursive_timed_mutex();
recursive_timed_mutex(const recursive_timed_mutex&) = delete;
recursive_timed_mutex& operator=(const recursive_timed_mutex&) = delete;
void lock();
bool try_lock();
template <class Rep, class Period>
bool try_lock_for(const chrono::duration<Rep, Period>& rel_time) noexcept;
template <class Clock, class Duration>
bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time) noexcept;
void unlock();
typedef implementation-defined native_handle_type;
native_handle_type native_handle();
};
}
1.5 std::lock_guard
类摘要
namespace std {
template <class Mutex>
class lock_guard {
public:
typedef Mutex mutex_type;
explicit lock_guard(mutex_type& m);
lock_guard(mutex_type& m, adopt_lock_t) noexcept;
~lock_guard();
lock_guard(lock_guard const&) = delete;
lock_guard& operator=(lock_guard const&) = delete;
private:
mutex_type& pm; // exposition only
};
}
1.6 std::unique_lock
类摘要
namespace std {
template <class Mutex>
class unique_lock {
public:
typedef Mutex mutex_type;
// 构造/拷贝/析构:
unique_lock() noexcept;
explicit unique_lock(mutex_type& m);
unique_lock(mutex_type& m, defer_lock_t) noexcept;
unique_lock(mutex_type& m, try_to_lock_t) noexcept;
unique_lock(mutex_type& m, adopt_lock_t) noexcept;
template <class Clock, class Duration>
unique_lock(mutex_type& m, const chrono::time_point<Clock, Duration>& abs_time) noexcept;
template <class Rep, class Period>
unique_lock(mutex_type& m, const chrono::duration<Rep, Period>& rel_time) noexcept;
~unique_lock();
unique_lock(unique_lock const&) = delete;
unique_lock& operator=(unique_lock const&) = delete;
unique_lock(unique _lock&& u) noexcept;
unique_lock& operator=(unique_lock&& u) noexcept;
// 上锁操作:
void lock();
bool try_lock();
template <class Rep, class Period>
bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
template <class Clock, class Duration>
bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
void unlock();
// 修改操作
void swap(unique_lock& u) noexcept;
mutex_type *release() noexcept;
// observers:
bool owns_lock() const noexcept;
explicit operator bool () const noexcept;
mutex_type* mutex() const noexcept;
private:
mutex_type *pm; // exposition only
bool owns; // exposition only
};
template <class Mutex>
void swap(unique_lock<Mutex>& x, unique_lock<Mutex>& y) noexcept;
}
1.7 std::scoped_lock 类摘要
template<class... MutexTypes>
class scoped_lock {
public:
using mutex_type = Mutex; // If MutexTypes... consists of the single type Mutex
explicit scoped_lock(MutexTypes&... m);
explicit scoped_lock(adopt_lock_t, MutexTypes&... m);
~scoped_lock();
scoped_lock(const scoped_lock&) = delete;
scoped_lock& operator=(const scoped_lock&) = delete;
private:
tuple<MutexTypes&...> pm; // exposition only
};
2. 互斥量详解
2.1 std::mutex
介绍
std::mutex
是 C++11 中最基本的互斥量,std::mutex
对象提供了独占所有权的特性——即不支持递归地对 std::mutex
对象上锁,而 std::recursive_lock
则可以递归地对互斥量对象上锁。
2.1.1 std::mutex
的成员函数
-
构造函数,std::mutex不允许拷贝构造,也不允许 move 拷贝,最初产生的 mutex 对象是处于 unlocked 状态的。
-
lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:(1). 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,该线程一直拥有该锁。(2). 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
-
unlock(), 解锁,释放对互斥量的所有权。
-
try_lock(),尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻塞。线程调用该函数也会出现下面 3 种情况,
- 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock 释放互斥量。
- 如果当前互斥量被其他线程锁住,则当前调用线程返回 false,而并不会被阻塞掉。
- 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
下面给出一个与 std::mutex 的小例子
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
volatile int counter(0); // non-atomic counter
std::mutex mtx; // locks access to counter
void attempt_10k_increases() {
for (int i=0; i<10000; ++i) {
if (mtx.try_lock()) { // only increase if currently not locked:
++counter;
mtx.unlock();
}
}
}
int main (int argc, const char* argv[]) {
std::thread threads[10];
for (int i=0; i<10; ++i)
threads[i] = std::thread(attempt_10k_increases);
for (auto& th : threads) th.join();
std::cout << counter << " successful increases of the counter.\n";
return 0;
}
2.2 std::recursive_mutex
介绍
std::recursive_mutex
与 std::mutex
一样,也是一种可以被上锁的对象,但是和 std::mutex
不同的是,std::recursive_mutex
允许同一个线程对互斥量多次上锁(即递归上锁),来获得对互斥量对象的多层所有权,std::recursive_mutex
释放互斥量时需要调用与该锁层次深度相同次数的 unlock()
,可理解为 lock()
次数和 unlock()
次数相同,除此之外,std::recursive_mutex
的特性和 std::mutex
大致相同。
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
class counter
{
public:
counter() : count(0) { }
int add(int val) {
std::lock_guard<std::recursive_mutex> lock(mutex);
count += val;
return count;
}
int increment() {
std::lock_guard<std::recursive_mutex> lock(mutex);
return add(1);
}
private:
std::recursive_mutex mutex;
int count;
};
counter c;
void change_count()
{
std::cout << "count == " << c.increment() << std::endl;
}
int main(int, char*[])
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(change_count);
for (auto& th : threads) th.join();
return 0;
}
2.3 std::time_mutex 介绍
std::time_mutex
比 std::mutex
多了两个成员函数,try_lock_for()
,try_lock_until()
。
try_lock_for
函数接受一个时间范围,表示在这一段时间范围之内线程如果没有获得锁则被阻塞住(与 std::mutex
的 try_lock()
不同,try_lock 如果被调用时没有获得锁则直接返回 false
),如果在此期间其他线程释放了锁,则该线程可以获得对互斥量的锁,如果超时(即在指定时间内还是没有获得锁),则返回 false
。
try_lock_until
函数则接受一个时间点作为参数,在指定时间点未到来之前线程如果没有获得锁则被阻塞住,如果在此期间其他线程释放了锁,则该线程可以获得对互斥量的锁,如果超时(即在指定时间内还是没有获得锁),则返回 false
。
下面的小例子说明了 std::time_mutex
的用法
#include <iostream> // std::cout
#include <chrono> // std::chrono::milliseconds
#include <thread> // std::thread
#include <mutex> // std::timed_mutex
std::timed_mutex mtx;
void fireworks() {
// waiting to get a lock: each thread prints "-" every 200ms:
while (!mtx.try_lock_for(std::chrono::milliseconds(200))) {
std::cout << "-";
}
// got a lock! - wait for 1s, then this thread prints "*"
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "*\n";
mtx.unlock();
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(fireworks);
for (auto& th : threads) th.join();
return 0;
}
2.4 std::recursive_timed_mutex
介绍
和 std:recursive_mutex
与 std::mutex
的关系一样,std::recursive_timed_mutex
的特性也可以从 std::timed_mutex
推导出来
3. 锁类型详解
3.1 std::lock_guard 介绍
lock_guard
构造函数如下表所示:
locking (1) | explicit lock_guard(mutex_type& m); |
---|---|
adopting (2) | lock_guard(mutex_type& m, adopt_lock_t tag); |
copy [deleted](3) | lock_guard(const lock_guard&) = delete; |
- locking 初始化,
lock_guard
对象管理 Mutex 对象 m,并在构造时对 m 进行上锁(调用m.lock()
)。 - adopting 初始化,
lock_guard
对象管理 Mutex 对象 m,与 locking 初始化(1) 不同的是,在构造时不会去对m进行上锁,而是认为当前线程已经对m上过锁了。 - 拷贝构造,
lock_guard
对象的拷贝构造和移动构造(move construction)均被禁用,因此lock_guard
对象不可被拷贝构造或移动构造。
来看一个简单的例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock_guard, std::adopt_lock
std::mutex mtx; // mutex for critical section
void print_thread_id (int id) {
mtx.lock();
std::lock_guard<std::mutex> lck(mtx, std::adopt_lock);
std::cout << "thread #" << id << '\n';
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return 0;
}
在 print_thread_id
中,我们首先对 mtx 进行上锁操作(mtx.lock();
),然后用 mtx 对象构造一个 lock_guard
对象(std::lock_guard<std::mutex> lck(mtx, std::adopt_lock);
),注意此时 Tag 参数为 std::adopt_lock
,表明当前线程已经获得了锁,此后 mtx 对象的解锁操作交由 lock_guard
对象 lck 来管理,在 lck 的生命周期结束之后,mtx 对象会自动解锁。
lock_guard
最大的特点就是安全易于使用,在异常抛出的时候通过 lock_guard
对象管理的 Mutex 可以得到正确地解锁。
请看下面例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock_guard
#include <stdexcept> // std::logic_error
std::mutex mtx;
void print_even (int x) {
if (x%2==0) std::cout << x << " is even\n";
else throw (std::logic_error("not even"));
}
void print_thread_id (int id) {
try {
// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
std::lock_guard<std::mutex> lck (mtx);
print_even(id);
}
catch (std::logic_error&) {
std::cout << "[exception caught]\n";
}
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return 0;
}
3.2 std::unique_lock
介绍
lock_guard
最大的特点就是安全简单,但是 lock_guard
最大的缺点也是简单,没有给程序员提供足够的灵活度,因此,C++11 标准中定义了另外一个与 Mutex RAII 相关类 unique_lock
,该类与 lock_guard
类相似,也很方便线程对互斥量上锁,但它提供了更好的上锁和解锁控制。
顾名思义,unique_lock
对象以独占所有权的方式( unique owership)管理 mutex 对象的上锁和解锁操作,所谓独占所有权,就是没有其他的 unique_lock
对象同时拥有某个 mutex 对象的所有权。
在构造(或移动(move)赋值)时,unique_lock
对象需要传递一个 Mutex 对象作为它的参数,新创建的 unique_lock
对象负责传入的 Mutex 对象的上锁和解锁操作。
std::unique_lock
对象也能保证在其自身析构时它所管理的 Mutex 对象能够被正确地解锁(即使没有显式地调用 unlock
函数)。因此,和 lock_guard
一样,这也是一种简单而又安全的上锁和解锁方式,尤其是在程序抛出异常后先前已被上锁的 Mutex 对象可以正确进行解锁操作,极大地简化了程序员编写与 Mutex 相关的异常处理代码。
值得注意的是,unique_lock
对象同样也不负责管理 Mutex 对象的生命周期,unique_lock
对象只是简化了 Mutex 对象的上锁和解锁操作,方便线程对互斥量上锁,即在某个 unique_lock
对象的声明周期内,它所管理的锁对象会一直保持上锁状态;而 unique_lock
的生命周期结束之后,它所管理的锁对象会被解锁,这一点和 lock_guard
类似,但 unique_lock
给程序员提供了更多的自由。
3.2.1 std::unique_lock
构造函数
std::unique_lock
的构造函数的数目相对来说比 std::lock_guard
多,其中一方面也是因为 std::unique_lock
更加灵活,从而在构造 std::unique_lock
对象时可以接受额外的参数。总地来说,std::unique_lock
构造函数如下:
default (1) | unique_lock() noexcept; |
---|---|
locking (2) | explicit unique_lock(mutex_type& m); |
try-locking (3) | unique_lock(mutex_type& m, try_to_lock_t tag); |
deferred (4) | unique_lock(mutex_type& m, defer_lock_t tag) noexcept; |
adopting (5) | unique_lock(mutex_type& m, adopt_lock_t tag); |
locking for (6) | template <class Rep, class Period> unique_lock(mutex_type& m, const chrono::duration<Rep,Period>& rel_time); |
locking until (7) | template <class Clock, class Duration> unique_lock(mutex_type& m, const chrono::time_point<Clock,Duration>& abs_time); |
copy [deleted] (8) | unique_lock(const unique_lock&) = delete; |
move (9) | unique_lock(unique_lock&& x); |
- (1) 默认构造函数,新创建的
unique_lock
对象不管理任何 Mutex 对象。 - (2) locking 初始化,新创建的
unique_lock
对象管理 Mutex 对象 m,并尝试调用m.lock()
对 Mutex 对象进行上锁,如果此时另外某个unique_lock
对象已经管理了该 Mutex 对象 m,则当前线程将会被阻塞。 - (3) try-locking 初始化,新创建的
unique_lock
对象管理 Mutex 对象 m,并尝试调用m.try_lock()
对 Mutex 对象进行上锁,但如果上锁不成功,并不会阻塞当前线程。 - (4) deferred 初始化,新创建的
unique_lock
对象管理 Mutex 对象 m,但是在初始化的时候并不锁住 Mutex 对象。 m 是一个没有被当前线程锁住的 Mutex 对象。 - (5) adopting 初始化,新创建的
unique_lock
对象管理 Mutex 对象 m, m 应该是一个已经被当前线程锁住的 Mutex 对象。(并且当前新创建的unique_lock
对象拥有对锁(Lock)的所有权)。 - (6) 试图通过调用
m.try_lock_for(rel_time)
来锁住 Mutex 对象,在rel_time消逝前或获取lock前一直阻塞。新创建的unique_lock
对象管理 Mutex 对象 m。 - (7) 试图通过调用
m.try_lock_until(abs_time)
来锁住 Mutex 对象,在到达某个时间点(abs_time
)前或获取lock前一直阻塞。新创建的unique_lock
对象管理 Mutex 对象m。 - (8) 拷贝构造 [被禁用],unique_lock 对象不能被拷贝构造。
- (9) 移动(move)构造,新创建的
unique_lock
对象获得了由 x 所管理的 Mutex 对象的所有权(包括当前 Mutex 的状态)。调用 move 构造之后, x 对象如同通过默认构造函数所创建的,就不再管理任何 Mutex 对象了。
综上所述,由 (2) 和 (5) 创建的 unique_lock
对象通常拥有 Mutex 对象的锁。而通过 (1) 和 (4) 创建的则不会拥有锁。通过 (3),(6) 和 (7) 创建的 unique_lock
对象,则在 lock
成功时获得锁。
关于 unique_lock
的构造函数,请看下面例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::lock, std::unique_lock
// std::adopt_lock, std::defer_lock
std::mutex foo,bar;
void task_a () {
std::lock (foo,bar); // simultaneous lock (prevents deadlock)
std::unique_lock<std::mutex> lck1 (foo,std::adopt_lock);
std::unique_lock<std::mutex> lck2 (bar,std::adopt_lock);
std::cout << "task a\n";
// (unlocked automatically on destruction of lck1 and lck2)
}
void task_b () {
// foo.lock(); bar.lock(); // replaced by:
std::unique_lock<std::mutex> lck1, lck2;
lck1 = std::unique_lock<std::mutex>(bar,std::defer_lock);
lck2 = std::unique_lock<std::mutex>(foo,std::defer_lock);
std::lock (lck1,lck2); // simultaneous lock (prevents deadlock)
std::cout << "task b\n";
// (unlocked automatically on destruction of lck1 and lck2)
}
int main ()
{
std::thread th1 (task_a);
std::thread th2 (task_b);
th1.join();
th2.join();
return 0;
}
3.2.2 std::unique_lock
移动(move assign)赋值操作
std::unique_lock
支持移动赋值(move assignment),但是普通的赋值被禁用了,
move (1) | unique_lock& operator= (unique_lock&& x) noexcept; |
---|---|
copy [deleted] (2) | unique_lock& operator= (const unique_lock&) = delete; |
移动赋值(move assignment)之后,由 x 所管理的 Mutex 对象及其状态将会被新的 std::unique_lock
对象取代。
如果被赋值的对象之前已经获得了它所管理的 Mutex 对象的锁,则在移动赋值(move assignment)之前会调用 unlock
函数释放它所占有的锁。
调用移动赋值(move assignment)之后, x 对象如同通过默认构造函数所创建的,也就不再管理任何 Mutex 对象了。请看下面例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
std::mutex mtx; // mutex for critical section
void print_fifty (char c) {
std::unique_lock<std::mutex> lck; // default-constructed
lck = std::unique_lock<std::mutex>(mtx); // move-assigned
for (int i=0; i<50; ++i) { std::cout << c; }
std::cout << '\n';
}
int main ()
{
std::thread th1 (print_fifty,'*');
std::thread th2 (print_fifty,'$');
th1.join();
th2.join();
return 0;
}
3.2.3 std::unique_lock 主要成员函数
由于 std::unique_lock
比 std::lock_guard
操作灵活,因此它提供了更多成员函数。具体分类如下:
- 上锁/解锁操作:
lock
,try_lock
,try_lock_for
,try_lock_until
和unlock
- 修改操作:移动赋值(move assignment)(前面已经介绍过了),交换(
swap
)(与另一个 std::unique_lock 对象交换它们所管理的 Mutex 对象的所有权),释放(release
)(返回指向它所管理的 Mutex 对象的指针,并释放所有权) - 获取属性操作:
owns_lock
(返回当前std::unique_lock
对象是否获得了锁)、operator bool()
(与 owns_lock 功能相同,返回当前std::unique_lock
对象是否获得了锁)、mutex(返回当前std::unique_lock
对象所管理的 Mutex 对象的指针)。
3.2.3.1 std::unique_lock::lock
上锁操作,调用它所管理的 Mutex 对象的 lock
函数。如果在调用 Mutex 对象的 lock 函数时该 Mutex 对象已被另一线程锁住,则当前线程会被阻塞,直到它获得了锁。
该函数返回时,当前的 unique_lock
对象便拥有了它所管理的 Mutex 对象的锁。如果上锁操作失败,则抛出 system_error
异常。
请看下面例子:
// unique_lock::lock/unlock
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock, std::defer_lock
std::mutex mtx; // mutex for critical section
void print_thread_id (int id) {
std::unique_lock<std::mutex> lck (mtx,std::defer_lock);
// critical section (exclusive access to std::cout signaled by locking lck):
lck.lock();
std::cout << "thread #" << id << '\n';
lck.unlock();
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return 0;
}
3.2.3.2 std::unique_lock::try_lock
上锁操作,调用它所管理的 Mutex 对象的 try_lock
函数,如果上锁成功,则返回 true,否则返回 false。
请看下面例子:
#include <iostream> // std::cout
#include <vector> // std::vector
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock, std::defer_lock
std::mutex mtx; // mutex for critical section
void print_star () {
std::unique_lock<std::mutex> lck(mtx,std::defer_lock);
// print '*' if successfully locked, 'x' otherwise:
if (lck.try_lock())
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;
}
3.2.3.3 std::unique_lock::try_lock_for
上锁操作,调用它所管理的 Mutex 对象的 try_lock_for
函数,如果上锁成功,则返回 true,否则返回 false。
请看下面例子:
#include <iostream> // std::cout
#include <chrono> // std::chrono::milliseconds
#include <thread> // std::thread
#include <mutex> // std::timed_mutex, std::unique_lock, std::defer_lock
std::timed_mutex mtx;
void fireworks () {
std::unique_lock<std::timed_mutex> lck(mtx,std::defer_lock);
// waiting to get a lock: each thread prints "-" every 200ms:
while (!lck.try_lock_for(std::chrono::milliseconds(200))) {
std::cout << "-";
}
// got a lock! - wait for 1s, then this thread prints "*"
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "*\n";
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(fireworks);
for (auto& th : threads) th.join();
return 0;
}
3.2.3.4 std::unique_lock::try_lock_until
上锁操作,调用它所管理的 Mutex 对象的 try_lock_until
函数,如果上锁成功,则返回 true,否则返回 false。
请看下面例子:
#include <iostream> // std::cout
#include <chrono> // std::chrono::milliseconds
#include <thread> // std::thread
#include <mutex> // std::timed_mutex, std::unique_lock, std::defer_lock
std::timed_mutex mtx;
void fireworks () {
std::unique_lock<std::timed_mutex> lck(mtx,std::defer_lock);
// waiting to get a lock: each thread prints "-" every 200ms:
while (!lck.try_lock_for(std::chrono::milliseconds(200))) {
std::cout << "-";
}
// got a lock! - wait for 1s, then this thread prints "*"
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::cout << "*\n";
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(fireworks);
for (auto& th : threads) th.join();
return 0;
}
3.2.3.5 std::unique_lock::unlock
解锁操作,调用它所管理的 Mutex 对象的 unlock
函数。
请看下面例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock, std::defer_lock
std::mutex mtx; // mutex for critical section
void print_thread_id (int id) {
std::unique_lock<std::mutex> lck (mtx,std::defer_lock);
// critical section (exclusive access to std::cout signaled by locking lck):
lck.lock();
std::cout << "thread #" << id << '\n';
lck.unlock();
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_thread_id,i+1);
for (auto& th : threads) th.join();
return 0;
}
3.2.3.6 std::unique_lock::release
返回指向它所管理的 Mutex 对象的指针,并释放所有权。
请看下面例子:
#include <iostream> // std::cout
#include <vector> // std::vector
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
std::mutex mtx;
int count = 0;
void print_count_and_unlock (std::mutex* p_mtx) {
std::cout << "count: " << count << '\n';
p_mtx->unlock();
}
void task() {
std::unique_lock<std::mutex> lck(mtx);
++count;
print_count_and_unlock(lck.release());
}
int main ()
{
std::vector<std::thread> threads;
for (int i=0; i<10; ++i)
threads.emplace_back(task);
for (auto& x: threads) x.join();
return 0;
}
3.2.3.7 std::unique_lock::owns_lock
返回当前 std::unique_lock
对象是否获得了锁。
请看下面例子:
#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.owns_lock())
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;
}
3.2.3.8 std::unique_lock::operator bool()
与 owns_lock
功能相同,返回当前 std::unique_lock
对象是否获得了锁。
请看下面例子:
#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;
}
3.2.3.9 std::unique_lock::mutex
返回当前 std::unique_lock
对象所管理的 Mutex 对象的指针。
请看下面例子:
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock, std::defer_lock
class MyMutex : public std::mutex {
int _id;
public:
MyMutex (int id) : _id(id) {}
int id() {return _id;}
};
MyMutex mtx (101);
void print_ids (int id) {
std::unique_lock<MyMutex> lck (mtx);
std::cout << "thread #" << id << " locked mutex " << lck.mutex()->id() << '\n';
}
int main ()
{
std::thread threads[10];
// spawn 10 threads:
for (int i=0; i<10; ++i)
threads[i] = std::thread(print_ids,i+1);
for (auto& th : threads) th.join();
return 0;
}
lock_guard和unique_lock的区别:
1>lock_guard只能在创建的时候lock一次,直到析构的时候unlock; unique_lock可以在析构前调用lock()和unlock()任意次。
2>unique_lock可以使用move assignment transfer ownership; lock_guard不能transfer ownership。
3.3 std::scoped_lock 介绍
C++17引入了std::scoped_lock, 它在创建时可以接受多个mutex, 并以std::lock方法的方式避免deadlock。
{
// safely locked as if using std::lock
std::scoped_lock<std::mutex, std::mutex> lock(mutex1, mutex2);
}
scoped_lock 构造函数如下表所示:
locking (1) | explicit scoped_lock( MutexTypes&... m ); |
---|---|
adopting (2) | scoped_lock( std::adopt_lock_t, MutexTypes&... m ); |
copy [deleted](3) | scoped_lock( const scoped_lock& ) = delete; |
- locking 初始化,如果sizeof...(MutexTypes)==0,不做任何操作。如果sizeof...(MutexTypes)==1,调用m.lock()。如果sizeof...(MutexTypes)>1,调用std::lock(m...)。
- adopting 初始化,scoped_lock对象管理 Mutex 对象 m,与 locking 初始化(1) 不同的是,在构造时不会去对m进行上锁,而是认为当前线程已经对m上过锁了。
- 拷贝构造,scoped_lock 对象的拷贝构造和移动构造(move construction)均被禁用,因此 scoped_lock 对象不可被拷贝构造或移动构造。
下面的例子是使用std::scoped_lock锁住成对的mutex并避免死锁
#include <mutex>
#include <thread>
#include <iostream>
#include <vector>
#include <functional>
#include <chrono>
#include <string>
struct Employee {
Employee(std::string id) : id(id) {}
std::string id;
std::vector<std::string> lunch_partners;
std::mutex m;
std::string output() const
{
std::string ret = "Employee " + id + " has lunch partners: ";
for( const auto& partner : lunch_partners )
ret += partner + " ";
return ret;
}
};
void send_mail(Employee &, Employee &)
{
// simulate a time-consuming messaging operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void assign_lunch_partner(Employee &e1, Employee &e2)
{
static std::mutex io_mutex;
{
std::lock_guard<std::mutex> lk(io_mutex);
std::cout << e1.id << " and " << e2.id << " are waiting for locks" << std::endl;
}
{
// use std::scoped_lock to acquire two locks without worrying about
// other calls to assign_lunch_partner deadlocking us
// and it also provides a convenient RAII-style mechanism
std::scoped_lock lock(e1.m, e2.m);
// Equivalent code 1 (using std::lock and std::lock_guard)
// std::lock(e1.m, e2.m);
// std::lock_guard<std::mutex> lk1(e1.m, std::adopt_lock);
// std::lock_guard<std::mutex> lk2(e2.m, std::adopt_lock);
// Equivalent code 2 (if unique_locks are needed, e.g. for condition variables)
// std::unique_lock<std::mutex> lk1(e1.m, std::defer_lock);
// std::unique_lock<std::mutex> lk2(e2.m, std::defer_lock);
// std::lock(lk1, lk2);
{
std::lock_guard<std::mutex> lk(io_mutex);
std::cout << e1.id << " and " << e2.id << " got locks" << std::endl;
}
e1.lunch_partners.push_back(e2.id);
e2.lunch_partners.push_back(e1.id);
}
send_mail(e1, e2);
send_mail(e2, e1);
}
int main()
{
Employee alice("alice"), bob("bob"), christina("christina"), dave("dave");
// assign in parallel threads because mailing users about lunch assignments
// takes a long time
std::vector<std::thread> threads;
threads.emplace_back(assign_lunch_partner, std::ref(alice), std::ref(bob));
threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(bob));
threads.emplace_back(assign_lunch_partner, std::ref(christina), std::ref(alice));
threads.emplace_back(assign_lunch_partner, std::ref(dave), std::ref(bob));
for (auto &thread : threads) thread.join();
std::cout << alice.output() << '\n' << bob.output() << '\n'
<< christina.output() << '\n' << dave.output() << '\n';
}
lock_guard已经不建议使用,推荐使用std::scoped_lock替代。