C++11并发指南01
C++11 自2011年已经发布以来快两年了,之前一直没怎么关注,直到最近几个月才看了一些 C++11 的新特性,今后几篇博客我都会写一些关于 C++11 的特性,算是记录一下自己学到的东西吧,和大家共勉。 相信 Linux 程序员都用过 Pthread, 但有了 C++11 的 std:thread以后,你可以在语言层面编写多线程程序了,直接的好处就是多线程程序的可移植性得到了很大的提高,所以作为一名 C++ 程序员,熟悉 C++11的多线程编程方式还是很有益处的。
引言
C++11 自2011年发布以来已经快两年了,之前一直没怎么关注,直到最近几个月才看了一些 C++11 的新特性,今后几篇博客我都会写一些关于 C++11的特性,算是记录一下自己学到的东西吧,和大家共勉。
相信 Linux 程序员都用过 Pthread, 但有了 C++11 的 std::thread以后,你可以在语言层面编写多线程程序了,直接的好处就是多线程程序的可移植性得到了很大的提高,所以作为一名 C++ 程序员,熟悉 C++11的多线程编程方式还是很有益处的。
如果你对 C++11 不太熟悉,建议先看看维基百科上关于 C++11 新特性的介绍,中文C++11介绍,英文C++11介绍,另外C++之父 Bjarne Stroustrup 的关于 C++11 的 FAQ 也是必看的,我也收集了一些关于C++11的资料,供大家查阅:
资料汇
- http://www.open-std.org/jtc1/sc22/wg21/
- C++0x/C++11 Support in GCC:http://gcc.gnu.org/projects/cxx0x.html
- What is C++0x:https://www2.research.att.com/~bs/what-is-2009.pdf
- Overview of the New C++:http://www.artima.com/shop/overview_of_the_new_cpp
- Overview of the New C++ (C++0x).pdf:http://ishare.iask.sina.com.cn/f/20120005.html?from=like
- A Brief Look at C++0x:http://www.artima.com/cppsource/cpp0x.html
- Summary of C++11 Feature Availability in gcc and MSVC:http://www.aristeia.com/C++11/C++11FeatureAvailability.htm
- C++ 11: Come Closer:http://www.codeproject.com/Articles/344282/Cplusplus-11-Come-Closer
- C++11 threads, locks and condition variables:http://www.codeproject.com/Articles/598695/Cplusplus11-threads-locks-and-condition-variables
- Move Semantics and Perfect Forwarding in C++11:http://www.codeproject.com/Articles/397492/Move-Semantics-and-Perfect-Forwarding-in-Cplusplus
- http://solarianprogrammer.com/categories/C++11/
- C++11 Concurrency:http://www.baptiste-wicht.com/2012/03/cpp11-concurrency-part1-start-threads/
- http://www.hpl.hp.com/personal/Hans_Boehm/misc_slides/sfacm-cleaned.pdf
- http://en.cppreference.com/w/cpp/thread
- http://isocpp.org/blog/2012/12/c11-a-cheat-sheet-alex-sinyakov
- The Biggest Changes in C++11:http://blog.smartbear.com/c-plus-plus/the-biggest-changes-in-c11-and-why-you-should-care/
- Ten C++11 Features Every C++ Developer Should Use:http://www.codeproject.com/Articles/570638/Ten-Cplusplus11-Features-Every-Cplusplus-Developer
- C++11 – A Glance [part 1 of n]:http://www.codeproject.com/Articles/312029/Cplusplus11-A-Glance-part-1-of-n
- C++11 – A Glance [part 2 of n]:http://www.codeproject.com/Articles/314415/Cplusplus11-A-Glance-part-2-of-n
- C++11(及现代C++风格)和快速迭代式开发:http://mindhacks.cn/2012/08/27/modern-cpp-practices/
- Lambda Functions in C++11 - the Definitive Guide:http://www.cprogramming.com/c++11/c++11-lambda-closures.html
- Better types in C++11 - nullptr, enum classes (strongly typed enumerations) and cstdint:http://www.cprogramming.com/c++11/c++11-nullptr-strongly-typed-enum-class.html
- Rvalue-references-and-move-semantics-in-c++11:http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html
- http://www.gotw.ca/publications/index.htm
- http://www.devx.com/SpecialReports/Door/38865
- Multi-threading in C++0x:http://accu.org/index.php/journals/1584
- C++ 0X feature summary cheat sheat:http://www.iesensor.com/blog/2011/05/31/c-0x-feature-summary-cheat-sheat/
- Multithreading in C++0x part 1: Starting Threads:http://www.justsoftwaresolutions.co.uk/threading/multithreading-in-c++0x-part-1-starting-threads.html
- http://en.cppreference.com/w/cpp/thread
- http://www.cplusplus.com/reference/multithreading/
好了,下面来说正题吧 ;-)
与 C++11 多线程相关的头文件
C++11 新标准中引入了四个头文件来支持多线程编程,他们分别是<atomic>,<thread>,<mutex>,<condition_variable>和<future>。
<atomic>:该头文主要声明了两个类,std::atomic和std::atomic_flag,另外还声明了一套 C 风格的原子类型和与 C 兼容的原子操作的函数。<thread>:该头文件主要声明了 std::thread 类,另外std::this_thread命名空间也在该头文件中。<mutex>:该头文件主要声明了与互斥量(mutex)相关的类,包括 std::mutex 系列类,std::lock_guard,std::unique_lock, 以及其他的类型和函数。<condition_variable>:该头文件主要声明了与条件变量相关的类,包括std::condition_variable和std::condition_variable_any。<future>:该头文件主要声明了std::promise,std::package_task两个Provider 类,以及std::future和std::shared_future两个 Future 类,另外还有一些与之相关的类型和函数,std::async() 函数就声明在此头文件中。
std::thread "Hello world"
下面是一个最简单的使用 std::thread 类的例子:
#include <stdio.h>
#include <stdlib.h>
#include <iostream> // std::cout
#include <thread> // std::thread
void thread_task() {
std::cout << "hello thread" << std::endl;
}
/*
* === FUNCTION =========================================================
* Name: main
* Description: program entry routine.
* ========================================================================
*/
int main(int argc, const char *argv[])
{
std::thread t(thread_task);
t.join();
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
Makefile 如下:
all:Thread
CC=g++
CPPFLAGS=-Wall -std=c++11 -ggdb
LDFLAGS=-pthread
Thread:Thread.o
$(CC) $(LDFLAGS) -o $@ $^
Thread.o:Thread.cc
$(CC) $(CPPFLAGS) -o $@ -c $^
.PHONY:
clean
clean:
rm Thread.o Thread
注意在 Linux GCC4.6 环境下,编译时需要加 -pthread,否则执行时会出现:
$ ./Thread
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
Aborted (core dumped)
原因是 GCC 默认没有加载 pthread 库,据说在后续的版本中可以不用在编译时添加 -pthread 选项。
更多的有关 C++11 Concurrency 的介绍将在后续的一系列博客中写出,希望自己勤快一点吧 ;-)
原文出处:C++11并发指南二(std::thread 详解)
上一篇博客《C++11 并发指南一(C++11 多线程初探)》中只是提到了 std::thread的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用法。
上一篇博客《C++11 并发指南一(C++11多线程初探)》中只是提到了 std::thread的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用法。
std::thread 在
std::thread 构造
| default (1) |
thread() noexcept; |
|---|---|
| initialization (2) |
template <class Fn, class... Args> explicit thread (Fn&& fn, Args&&... args); |
| copy [deleted] (3) |
thread (const thread&) = delete; |
| move (4) |
thread (thread&& x) noexcept; |
- (1). 默认构造函数,创建一个空的 thread 执行对象。
- (2). 初始化构造函数,创建一个 thread对象,该 thread对象可被 joinable,新产生的线程会调用 fn 函数,该函数的参数由 args 给出。
- (3). 拷贝构造函数(被禁用),意味着 thread 不可被拷贝构造。
- (4). move 构造函数,move 构造函数,调用成功之后 x 不代表任何 thread 执行对象。
- 注意:可被 joinable 的 thread 对象必须在他们销毁之前被主线程 join 或者将其设置为 detached.
std::thread各种构造函数例子如下(参考):
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << n << " executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
move 赋值操作
| move (1) |
thread& operator= (thread&& rhs) noexcept; |
|---|---|
| copy [deleted] (2) |
thread& operator= (const thread&) = delete; |
- (1). move 赋值操作,如果当前对象不可 joinable,需要传递一个右值引用(rhs)给 move 赋值操作;如果当前对象可被 joinable,则 terminate() 报错。
- (2). 拷贝赋值操作被禁用,thread 对象不可被拷贝。
请看下面的例子:
#include <stdio.h>
#include <stdlib.h>
#include <chrono> // std::chrono::seconds
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
void thread_task(int n) {
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "hello thread "
<< std::this_thread::get_id()
<< " paused " << n << " seconds" << std::endl;
}
/*
* === FUNCTION =========================================================
* Name: main
* Description: program entry routine.
* ========================================================================
*/
int main(int argc, const char *argv[])
{
std::thread threads[5];
std::cout << "Spawning 5 threads...\n";
for (int i = 0; i < 5; i++) {
threads[i] = std::thread(thread_task, i + 1);
}
std::cout << "Done spawning threads! Now wait for them to join\n";
for (auto& t: threads) {
t.join();
}
std::cout << "All threads joined.\n";
return EXIT_SUCCESS;
} /* ---------- end of function main ---------- */
其他成员函数
- get_id获取线程ID。
- joinable检查线程是否可被join。
- joinJoin线程。
- detachDetach线程
- swapSwap线程 。
- native_handle返回native handle。
- hardware_concurrency[static]检测硬件并发特性。
上一篇《C++11 并发指南二(std::thread 详解)》中主要讲到了 std::thread 的一些用法,并给出了两个小例子,本文将介绍std::muetx 的用法。 Mutex 又称互斥量,C++ 11中与 Mutex 相关的类(包括锁类型)和函数都声明在 头文件中,所以如果你需要使用std::mutex,就必须包含 头文件。
上一篇《C++11 并发指南二(std::thread详解)》中主要讲到了 std::thread的一些用法,并给出了两个小例子,本文将介绍 std::mutex 的用法。
Mutex 又称互斥量,C++ 11中与 Mutex 相关的类(包括锁类型)和函数都声明在
头文件介绍
Mutex 系列类(四种)
- std::mutex,最基本的 Mutex 类。
- std::recursive_mutex,递归 Mutex 类。
- std::time_mutex,定时 Mutex 类。
- std::recursive_timed_mutex,定时递归 Mutex 类。
Lock 类(两种)
- std::lock_guard,与 Mutex RAII 相关,方便线程对互斥量上锁。
- std::unique_lock,与 Mutex RAII 相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。
其他类型
- std::once_flag
- std::adopt_lock_t
- std::defer_lock_t
- std::try_to_lock_t
函数
- std::try_lock,尝试同时对多个互斥量上锁。
- std::lock,可以同时对多个互斥量上锁。
- std::call_once,如果多个线程需要同时调用某个函数,call_once 可以保证多个线程对该函数只调用一次。
std::mutex 介绍
下面以 std::mutex 为例介绍 C++11 中的互斥量用法。
std::mutex 是C++11 中最基本的互斥量,std::mutex 对象提供了独占所有权的特性——即不支持递归地对 std::mutex 对象上锁,而 std::recursive_lock则可以递归地对互斥量对象上锁。
std::mutex 的成员函数
- 构造函数,std::mutex不允许拷贝构造,也不允许 move 拷贝,最初产生的 mutex 对象是处于 unlocked 状态的。
- lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:(1). 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,该线程一直拥有该锁。(2). 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
- unlock(), 解锁,释放对互斥量的所有权。
- try_lock(),尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻塞。线程调用该函数也会出现下面 3 种情况,(1). 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock 释放互斥量。(2). 如果当前互斥量被其他线程锁住,则当前调用线程返回 false,而并不会被阻塞掉。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(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;
}
std::recursive_mutex 介绍
std::recursive_mutex与 std::mutex 一样,也是一种可以被上锁的对象,但是和 std::mutex不同的是,std::recursive_mutex允许同一个线程对互斥量多次上锁(即递归上锁),来获得对互斥量对象的多层所有权,std::recursive_mutex释放互斥量时需要调用与该锁层次深度相同次数的 unlock(),可理解为 lock() 次数和 unlock()次数相同,除此之外,std::recursive_mutex的特性和 std::mutex 大致相同。
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;
}
std::recursive_timed_mutex 介绍
和std:recursive_mutex与 std::mutex 的关系一样,std::recursive_timed_mutex的特性也可以从std::timed_mutex推导出来,感兴趣的同鞋可以自行查阅。 ;-)
std::lock_guard 介绍
与 Mutex RAII相关,方便线程对互斥量上锁。例子(参考):
#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;
}
std::unique_lock 介绍
与 Mutex RAII 相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。例子(参考):
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
std::mutex mtx; // mutex for critical section
void print_block (int n, char c) {
// critical section (exclusive access to std::cout signaled by lifetime of lck):
std::unique_lock<std::mutex> lck (mtx);
for (int i=0; i<n; ++i) {
std::cout << c;
}
std::cout << '\n';
}
int main ()
{
std::thread th1 (print_block,50,'*');
std::thread th2 (print_block,50,'$');
th1.join();
th2.join();
return 0;
}
好了,本文暂时讲到这里,还剩下std::try_lock,std::lock,std::call_once三个函数没有讲到,留在下一篇博客中讲吧 ;-)
原文出处:C++11并发指南三(Lock详解)
在 《C++11 并发指南三(std::mutex 详解)》一文中我们主要介绍了 C++11 标准中的互斥量(Mutex),并简单介绍了一下两种锁类型。本节将详细介绍一下 C++11 标准的的锁类型。
在 《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_guard 介绍
std::lock_gurad是 C++11 中定义的模板类。定义如下:
template <``class Mutex> ``class lock_guard;
lock_guard对象通常用于管理某个锁(Lock)对象,因此与 Mutex RAII 相关,方便线程对互斥量上锁,即在某个lock_guard对象的声明周期内,它所管理的锁对象会一直保持上锁状态;而lock_guard的生命周期结束之后,它所管理的锁对象会被解锁(注:类似shared_ptr`等智能指针管理动态分配的内存资源 )。
模板参数 Mutex 代表互斥量类型,例如 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对象构造时,传入的 Mutex 对象(即它所管理的 Mutex 对象)会被当前线程锁住。在lock_guard对象被析构时,它所管理的 Mutex 对象会自动解锁,由于不需要程序员手动调用 lock 和 unlock 对 Mutex进行上锁和解锁操作,因此这也是最简单安全的上锁和解锁方式,尤其是在程序抛出异常后先前已被上锁的 Mutex 对象可以正确进行解锁操作,极大地简化了程序员编写与 Mutex 相关的异常处理代码。
值得注意的是,lock_guard对象并不负责管理 Mutex 对象的生命周期,lock_guard对象只是简化了 Mutex 对象的上锁和解锁操作,方便线程对互斥量上锁,即在某个lock_guard对象的声明周期内,它所管理的锁对象会一直保持上锁状态;而lock_guard的生命周期结束之后,它所管理的锁对象会被解锁。
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) 不同的是, Mutex 对象 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;
}
std::unique_lock 介绍
但是 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给程序员提供了更多的自由,我会在下面的内容中给大家介绍unique_lock的用法。
另外,与lock_guard一样,模板参数 Mutex 代表互斥量类型,例如 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)。
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) 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 <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;
}
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;
}
std::unique_lock 主要成员函数
本节我们来看看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 对象的指针)。
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;
}
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;
}
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;
}
std::unique_lock::try_lock_until
上锁操作,调用它所管理的 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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
好了,本文先介绍到这里,我们基本上介绍完了 C++11 多线程编程中两种最基本的锁类型,后面我会继续更新有关 C++11并发编程的博客,希望感兴趣的同学继续关注 ;-)