c++11关于并发引入了好多好东西,这里按照以下顺序介绍:html
c++11以前你可能使用pthread_xxx来建立线程,繁琐且不易读,c++11引入了std::thread来建立线程,支持对线程join或者detach。直接看代码:ios
#include <iostream> #include <thread> using namespace std; int main() { auto func = []() { for (int i = 0; i < 10; ++i) { cout << i << " "; } cout << endl; }; std::thread t(func); if (t.joinable()) { t.detach(); } auto func1 = [](int k) { for (int i = 0; i < k; ++i) { cout << i << " "; } cout << endl; }; std::thread tt(func1, 20); if (tt.joinable()) { // 检查线程能否被join tt.join(); } return 0; }
上述代码中,函数func和func1运行在线程对象t和tt中,从刚建立对象开始就会新建一个线程用于执行函数,调用join函数将会阻塞主线程,直到线程函数执行结束,线程函数的返回值将会被忽略。若是不但愿线程被阻塞执行,能够调用线程对象的detach函数,表示将线程和线程对象分离。c++
若是没有调用join或者detach函数,假如线程函数执行时间较长,此时线程对象的生命周期结束调用析构函数清理资源,这时可能会发生错误,这里有两种解决办法,一个是调用join(),保证线程函数的生命周期和线程对象的生命周期相同,另外一个是调用detach(),将线程和线程对象分离,这里须要注意,若是线程已经和对象分离,那咱们就再也没法控制线程何时结束了,不能再经过join来等待线程执行完。编程
这里能够对thread进行封装,避免没有调用join或者detach可致使程序出错的状况出现:promise
class ThreadGuard { public: enum class DesAction { join, detach }; ThreadGuard(std::thread&& t, DesAction a) : t_(std::move(t)), action_(a){}; ~ThreadGuard() { if (t_.joinable()) { if (action_ == DesAction::join) { t_.join(); } else { t_.detach(); } } } ThreadGuard(ThreadGuard&&) = default; ThreadGuard& operator=(ThreadGuard&&) = default; std::thread& get() { return t_; } private: std::thread t_; DesAction action_; }; int main() { ThreadGuard t(std::thread([]() { for (int i = 0; i < 10; ++i) { std::cout << "thread guard " << i << " "; } std::cout << std::endl;}), ThreadGuard::DesAction::join); return 0; }
c++11还提供了获取线程id,或者系统cpu个数,获取thread native_handle,使得线程休眠等功能安全
std::thread t(func); cout << "当前线程ID " << t.get_id() << endl; cout << "当前cpu个数 " << std::thread::hardware_concurrency() << endl; auto handle = t.native_handle();// handle可用于pthread相关操做 std::this_thread::sleep_for(std::chrono::seconds(1));
std::mutex是一种线程同步的手段,用于保存多线程同时操做的共享数据。多线程
mutex分为四种:并发
拿一个std::mutex和std::timed_mutex举例吧,别的都是相似的使用方式:异步
std::mutex:async
#include <iostream> #include <mutex> #include <thread> using namespace std; std::mutex mutex_; int main() { auto func1 = [](int k) { mutex_.lock(); for (int i = 0; i < k; ++i) { cout << i << " "; } cout << endl; mutex_.unlock(); }; std::thread threads[5]; for (int i = 0; i < 5; ++i) { threads[i] = std::thread(func1, 200); } for (auto& th : threads) { th.join(); } return 0; }
std::timed_mutex:
#include <iostream> #include <mutex> #include <thread> #include <chrono> using namespace std; std::timed_mutex timed_mutex_; int main() { auto func1 = [](int k) { timed_mutex_.try_lock_for(std::chrono::milliseconds(200)); for (int i = 0; i < k; ++i) { cout << i << " "; } cout << endl; timed_mutex_.unlock(); }; std::thread threads[5]; for (int i = 0; i < 5; ++i) { threads[i] = std::thread(func1, 200); } for (auto& th : threads) { th.join(); } return 0; }
这里主要介绍两种RAII方式的锁封装,能够动态的释放锁资源,防止线程因为编码失误致使一直持有锁。
c++11主要有std::lock_guard和std::unique_lock两种方式,使用方式都相似,以下:
#include <iostream> #include <mutex> #include <thread> #include <chrono> using namespace std; std::mutex mutex_; int main() { auto func1 = [](int k) { // std::lock_guard<std::mutex> lock(mutex_); std::unique_lock<std::mutex> lock(mutex_); for (int i = 0; i < k; ++i) { cout << i << " "; } cout << endl; }; std::thread threads[5]; for (int i = 0; i < 5; ++i) { threads[i] = std::thread(func1, 200); } for (auto& th : threads) { th.join(); } return 0; }
std::lock_gurad相比于std::unique_lock更加轻量级,少了一些成员函数,std::unique_lock类有unlock函数,能够手动释放锁,因此条件变量都配合std::unique_lock使用,而不是std::lock_guard,由于条件变量在wait时须要有手动释放锁的能力,具体关于条件变量后面会讲到。
c++11提供了原子类型std::atomic<T>,理论上这个T能够是任意类型,可是我平时只存放整形,别的还真的没用过,整形有这种原子变量已经足够方便,就不须要使用std::mutex来保护该变量啦。看一个计数器的代码:
struct OriginCounter { // 普通的计数器 int count; std::mutex mutex_; void add() { std::lock_guard<std::mutex> lock(mutex_); ++count; } void sub() { std::lock_guard<std::mutex> lock(mutex_); --count; } int get() { std::lock_guard<std::mutex> lock(mutex_); return count; } }; struct NewCounter { // 使用原子变量的计数器 std::atomic<int> count; void add() { ++count; // count.store(++count);这种方式也能够 } void sub() { --count; // count.store(--count); } int get() { return count.load(); } };
是否是使用原子变量更加方便了呢?
c++11提供了std::call_once来保证某一函数在多线程环境中只调用一次,它须要配合std::once_flag使用,直接看使用代码吧:
std::once_flag onceflag; void CallOnce() { std::call_once(onceflag, []() { cout << "call once" << endl; }); } int main() { std::thread threads[5]; for (int i = 0; i < 5; ++i) { threads[i] = std::thread(CallOnce); } for (auto& th : threads) { th.join(); } return 0; }
貌似把volatile放在并发里介绍不太合适,可是貌似不少人都会把volatile和多线程联系在一块儿,那就一块儿介绍下吧。
volatile一般用来创建内存屏障,volatile修饰的变量,编译器对访问该变量的代码一般再也不进行优化,看下面代码:
int *p = xxx; int a = *p; int b = *p;
a和b都等于p指向的值,通常编译器会对此作优化,把*p的值放入寄存器,就是传说中的工做内存(不是主内存),以后a和b都等于寄存器的值,可是若是中间p地址的值改变,内存上的值改变啦,但a,b仍是从寄存器中取的值(不必定,看编译器优化结果),这就不符合需求,因此在此对p加volatile修饰能够避免进行此类优化。
注意:volatile不能解决多线程安全问题,针对特种内存才须要使用volatile,它和atomic的特色以下:
条件变量是c++11引入的一种同步机制,它能够阻塞一个线程或者个线程,直到有线程通知或者超时才会唤醒正在阻塞的线程,条件变量须要和锁配合使用,这里的锁就是上面介绍的std::unique_lock。
这里使用条件变量实现一个CountDownLatch:
class CountDownLatch { public: explicit CountDownLatch(uint32_t count) : count_(count); void CountDown() { std::unique_lock<std::mutex> lock(mutex_); --count_; if (count_ == 0) { cv_.notify_all(); } } void Await(uint32_t time_ms = 0) { std::unique_lock<std::mutex> lock(mutex_); while (count_ > 0) { if (time_ms > 0) { cv_.wait_for(lock, std::chrono::milliseconds(time_ms)); } else { cv_.wait(lock); } } } uint32_t GetCount() const { std::unique_lock<std::mutex> lock(mutex_); return count_; } private: std::condition_variable cv_; mutable std::mutex mutex_; uint32_t count_ = 0; };
关于条件变量其实还涉及到通知丢失和虚假唤醒问题,由于不是本文的主题,这里暂不介绍,你们有须要能够留言。
c++11关于异步操做提供了future相关的类,主要有std::future、std::promise和std::packaged_task,std::future比std::thread高级些,std::future做为异步结果的传输通道,经过get()能够很方便的获取线程函数的返回值,std::promise用来包装一个值,将数据和future绑定起来,而std::packaged_task则用来包装一个调用对象,将函数和future绑定起来,方便异步调用。而std::future是不能够复制的,若是须要复制放到容器中可使用std::shared_future。
std::promise与std::future配合使用
#include <functional> #include <future> #include <iostream> #include <thread> using namespace std; void func(std::future<int>& fut) { int x = fut.get(); cout << "value: " << x << endl; } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); std::thread t(func, std::ref(fut)); prom.set_value(144); t.join(); return 0; }
std::packaged_task与std::future配合使用
#include <functional> #include <future> #include <iostream> #include <thread> using namespace std; int func(int in) { return in + 1; } int main() { std::packaged_task<int(int)> task(func); std::future<int> fut = task.get_future(); std::thread(std::move(task), 5).detach(); cout << "result " << fut.get() << endl; return 0; }
更多关于future的使用能够看我以前写的关于线程池和定时器的文章。
三者之间的关系
std::future用于访问异步操做的结果,而std::promise和std::packaged_task在future高一层,它们内部都有一个future,promise包装的是一个值,packaged_task包装的是一个函数,当须要获取线程中的某个值,可使用std::promise,当须要获取线程函数返回值,可使用std::packaged_task。
async是比future,packaged_task,promise更高级的东西,它是基于任务的异步操做,经过async能够直接建立异步的任务,返回的结果会保存在future中,不须要像packaged_task和promise那么麻烦,关于线程操做应该优先使用async,看一段使用代码:
#include <functional> #include <future> #include <iostream> #include <thread> using namespace std; int func(int in) { return in + 1; } int main() { auto res = std::async(func, 5); // res.wait(); cout << res.get() << endl; // 阻塞直到函数返回 return 0; }
使用async异步执行函数是否是方便多啦。
async具体语法以下:
async(std::launch::async | std::launch::deferred, func, args...);
第一个参数是建立策略:
若是不明确指定建立策略,以上两个都不是async的默认策略,而是未定义,它是一个基于任务的程序设计,内部有一个调度器(线程池),会根据实际状况决定采用哪一种策略。
若从 std::async 得到的 std::future 未被移动或绑定到引用,则在完整表达式结尾, std::future的析构函数将阻塞直至异步计算完成,实际上至关于同步操做:
std::async(std::launch::async, []{ f(); }); // 临时量的析构函数等待 f() std::async(std::launch::async, []{ g(); }); // f() 完成前不开始
注意
:关于async启动策略这里网上和各类书籍介绍的五花八门,这里会以cppreference为主。
有时候咱们若是想真正执行异步操做能够对async进行封装,强制使用std::launch::async策略来调用async。
template <typename F, typename... Args> inline auto ReallyAsync(F&& f, Args&&... params) { return std::async(std::launch::async, std::forward<F>(f), std::forward<Args>(params)...); }
关于c++11关于并发的新特性就介绍到这里,你们有问题能够给我留言~
https://blog.csdn.net/zhangzq...
https://zh.cppreference.com/w...
https://zhuanlan.zhihu.com/p/...
https://www.runoob.com/w3cnot...
https://zh.cppreference.com/w...
《深刻应用c++11:代码优化与工程级应用》
《Effective Modern C++》更多文章,请关注个人V X 公 主 号:程序喵大人,欢迎交流。