在 《C++11 并发指南三(std::mutex 详解)》一文中我们主要介绍了 C++11 标准中的互斥量(Mutex),并简单介绍了一下两种锁类型。本节将详细介绍一下 C++11 标准的锁类型。
C++11 标准为我们提供了两种基本的锁类型,分别如下:
std::lock_guard,与 Mutex RAII 相关,方便线程对互斥量上锁。
std::unique_lock,与 Mutex RAII 相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。
另外还提供了几个与锁类型相关的 Tag 类,分别如下:
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 {};,// constexpr 是 C++11 中的新关键字)
通常作为参数传入给 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 {};,// constexpr 是 C++11 中的新关键字)
通常作为参数传入给 unique_lock
或 lock_guard
的构造函数。后面我们会详细介绍以上三种 Tag 类型在配合 lock_gurad
与 unique_lock
使用时的区别。
std::lock_gurad
是 C++11 中定义的模板类。定义如下:
template class lock_guard{};
lock_guard
对象通常用于管理某个锁(Lock)对象,因此与Mutex RAII相关,方便线程对互斥量上锁,即在某个lock_guard 对象的声明周期内,它所管理的锁对象会一直保持上锁状态;而 lock_guard的生命周期结束之后,它所管理的锁对象会被解锁(注:类似shared_ptr 等智能指针管理动态分配的内存资源 )。std::mutex
类型,它应该是一个基本的BasicLockable
类型,标准库中定义几种基本的 BasicLockable
类型,分别 std::mutex
, std::recursive_mutex
, std::timed_mutex
,std::recursive_timed_mutex
(以上四种类型均已在上一篇博客中介绍)以及 std::unique_lock
(本文后续会介绍 std::unique_lock
)。(注:BasicLockable
类型的对象只需满足两种操作,lock
和 unlock
,另外还有 Lockable
类型,在 BasicLockable 类型的基础上新增了 try_lock 操作,因此一个满足 Lockable 的对象应支持三种操作:lock,unlock 和 try_lock;最后还有一种 TimedLockable 对象,在 Lockable 类型的基础上又新增了 try_lock_for 和 try_lock_until 两种操作,因此一个满足 TimedLockable 的对象应支持五种操作:lock, unlock, try_lock, try_lock_for, try_lock_until )。lock_guard 构造函数如下表所示:
locking (1) | explicit lock_guard (mutex_type& m); |
---|---|
adopting (2) | lock_guard (mutex_type& m, adopt_lock_t tag); |
copy deleted | lock_guard (const lock_guard&) = delete; |
我们来看一个简单的例子(参考):
#include // std::cout
#include // std::thread
#include // std::mutex, std::lock_guard, std::adopt_lockstd::mutex mtx; // mutex for critical sectionvoid print_thread_id (int id) {mtx.lock();std::lock_guard 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;
}
#include // std::cout
#include // std::thread
#include // std::mutex, std::lock_guard
#include // std::logic_errorstd::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 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;
}
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 |
locking until (7) | template |
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) locking 一段时间(duration)
新创建的 unique_lock 对象管理 Mutex 对象 m,并试图通过调用 m.try_lock_for(rel_time) 来锁住 Mutex 对象一段时间(rel_time)。
(7) locking 直到某个时间点(time point)
新创建的 unique_lock 对象管理 Mutex 对象m,并试图通过调用 m.try_lock_until(abs_time) 来在某个时间点(abs_time)之前锁住 Mutex 对象。
(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 // std::cout
#include // std::thread
#include // 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 lck1 (foo,std::adopt_lock);std::unique_lock 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 lck1, lck2;lck1 = std::unique_lock(bar,std::defer_lock);lck2 = std::unique_lock(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;
}
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 // std::cout
#include // std::thread
#include // std::mutex, std::unique_lockstd::mutex mtx; // mutex for critical sectionvoid print_fifty (char c) {std::unique_lock lck; // default-constructedlck = std::unique_lock(mtx); // move-assignedfor (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;
}
本节我们来看看 std::unique_lock 的主要成员函数。由于 std::unique_lock 比 std::lock_guard 操作灵活,因此它提供了更多成员函数。具体分类如下:
lock
,try_lock
,try_lock_for
,try_lock_until
和 unlock
上锁操作,调用它所管理的 Mutex 对象的 lock 函数。如果在调用 Mutex 对象的 lock 函数时该 Mutex 对象已被另一线程锁住,则当前线程会被阻塞,直到它获得了锁。
该函数返回时,当前的 unique_lock 对象便拥有了它所管理的 Mutex 对象的锁。如果上锁操作失败,则抛出 system_error 异常。
// unique_lock::lock/unlock
#include // std::cout
#include // std::thread
#include // std::mutex, std::unique_lock, std::defer_lockstd::mutex mtx; // mutex for critical sectionvoid print_thread_id (int id) {std::unique_lock 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;
}
上锁操作,调用它所管理的 Mutex 对象的 try_lock 函数,如果上锁成功,则返回 true,否则返回 false。
请看下面例子(参考):
#include // std::cout
#include // std::vector
#include // std::thread
#include // std::mutex, std::unique_lock, std::defer_lockstd::mutex mtx; // mutex for critical sectionvoid print_star () {std::unique_lock 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 threads;for (int i=0; i<500; ++i)threads.emplace_back(print_star);for (auto& x: threads) x.join();return 0;
}
上锁操作,调用它所管理的 Mutex 对象的 try_lock_for 函数,如果上锁成功,则返回 true,否则返回 false。
请看下面例子(参考):
#include // std::cout
#include // std::chrono::milliseconds
#include // std::thread
#include // std::timed_mutex, std::unique_lock, std::defer_lockstd::timed_mutex mtx;void fireworks () {std::unique_lock 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;
}
上锁操作,调用它所管理的 Mutex 对象的 try_lock_for 函数,如果上锁成功,则返回 true,否则返回 false。
请看下面例子(参考):
#include // std::cout
#include // std::chrono::milliseconds
#include // std::thread
#include // std::timed_mutex, std::unique_lock, std::defer_lockstd::timed_mutex mtx;void fireworks () {std::unique_lock 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;
}
解锁操作,调用它所管理的 Mutex 对象的 unlock 函数。
请看下面例子(参考):
#include // std::cout
#include // std::thread
#include // std::mutex, std::unique_lock, std::defer_lockstd::mutex mtx; // mutex for critical sectionvoid print_thread_id (int id) {std::unique_lock 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;
}
std::unique_lock::release
返回指向它所管理的 Mutex 对象的指针,并释放所有权。
请看下面例子(参考):
#include // std::cout
#include // std::vector
#include // std::thread
#include // std::mutex, std::unique_lockstd::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 lck(mtx);++count;print_count_and_unlock(lck.release());
}int main ()
{std::vector threads;for (int i=0; i<10; ++i)threads.emplace_back(task);for (auto& x: threads) x.join();return 0;
}
返回当前 std::unique_lock 对象是否获得了锁。
请看下面例子(参考):
#include // std::cout
#include // std::vector
#include // std::thread
#include // std::mutex, std::unique_lock, std::try_to_lockstd::mutex mtx; // mutex for critical sectionvoid print_star () {std::unique_lock 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 threads;for (int i=0; i<500; ++i)threads.emplace_back(print_star);for (auto& x: threads) x.join();return 0;
}
####std::unique_lock::operator bool()
与 owns_lock 功能相同,返回当前 std::unique_lock 对象是否获得了锁。
请看下面例子(参考):
#include // std::cout
#include // std::vector
#include // std::thread
#include // std::mutex, std::unique_lock, std::try_to_lockstd::mutex mtx; // mutex for critical sectionvoid print_star () {std::unique_lock lck(mtx,std::try_to_lock);// print '*' if successfully locked, 'x' otherwise: if (lck)std::cout << '*';else std::cout << 'x';
}int main ()
{std::vector threads;for (int i=0; i<500; ++i)threads.emplace_back(print_star);for (auto& x: threads) x.join();return 0;
}
返回当前 std::unique_lock 对象所管理的 Mutex 对象的指针。
请看下面例子(参考):
#include // std::cout
#include // std::thread
#include // std::mutex, std::unique_lock, std::defer_lockclass 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 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;
}
好了,本文先介绍到这里,我们基本上介绍完了 C++11 多线程编程中两种最基本的锁类型,后面我会继续更新有关 C++11 并发编程的博客,希望感兴趣的同学继续关注 😉
上一篇:Nextcloud的部署迁移过程
下一篇:react的知识点总结(1)