c++ 多线程——c++复习(十)
来源:互联网 发布:淘宝卖家发什么快递好 编辑:程序博客网 时间:2024/06/03 17:18
c++11使用的多线程非常简单:thread直接就可以创建一个线程。std::thread a;
join()
#include<iostream> #include<thread> #include<string> using namespace std; int main(int argc,const char * argv[]){ thread t([](){ cout<<"hello thread!\n"; }); t.join(); return 0 ; }
这里用到的join(),这是一个同步阻塞的方法,即使用了join()的时候,MainThread就被停止,直到a thread线程执行完。
detach()
#include<iostream>#include<thread>#include<string>#include <chrono>using namespace std;int main(int argc, const char * argv[]){ thread t([](){ cout<<"hello thread!\n"; }); t.join(); thread t2([](int n = 5){ this_thread::sleep_for(chrono::seconds(n)); cout<<"pause "<<n<<" seconds"<<endl;//this_thread获取当前线程,sleep_for:阻塞当前线程,时间不少于参数指定的时间;sleep_util:阻塞当前线程,时间为参数指定的时间; }); t2.detach(); int time = 2; this_thread::sleep_for(chrono::seconds(time)); cout<<"finished"<<endl; return 0 ;}
以上的代码则是用了detach();所以我们可以看到它是一个独立执行的线程。
但是这里要强调一个多线程中父子线程的关系问题:当主线程执行完毕退出的时候,无论子线程是否执行完毕,所有的子线程都会终止。
所以如果将time的值改成大于5,那么就会执行到第二个线程里打印出来的东西。
mutex互斥锁
#include<iostream>#include<thread>#include<string>#include <chrono>#include <vector>using namespace std;mutex mt;int main(int argc, const char * argv[]){ vector<thread> v(5); for(auto &i:v){ i = thread([](){ mt.lock(); cout<<"enter"<<endl; this_thread::sleep_for(chrono::seconds(3)); cout<<"onexit"<<endl; mt.unlock(); }); } for(auto &i:v) i.join(); return 0;}
mutex这个库包含与互斥量相关的东西。它提供了lock()和unlock()函数。(另外我们需要了解Recursive_mutex;Timed_mutex;Recursive_timed_mutex类)。
condition条件变量
#include<iostream>#include<thread>#include<string>#include <chrono>#include <condition_variable>using namespace std;condition_variable cv;mutex mt;int main(int argc, const char * argv[]){ thread t1([](){ unique_lock<mutex> lock(mt); cv.wait(lock); cout<<"t1 say hi!"<<endl; }); this_thread::sleep_for(chrono::seconds(2)); thread t2([](){ cout<<"t2 say hi!"<<endl; this_thread::sleep_for(chrono::seconds(2)); cv.notify_all(); }); t1.join(),t2.join(); return 0;}
当一个线程要等待另一个线程完成某个操作的时候,可以使用条件变量。条件变量可以将一个或多个线程进入阻塞状态,直到收到另一个线程的通知或者超时才能退出阻塞状态。
一个线程等待的满足条件:首先获得unique_lock锁。该锁将会传递给wait()方法,然后wait()方法会释放互斥量并将当前线程暂停,直到信号变量得到相应的信号。接到信号后线程就被重新唤醒。
另外一个线程发送信号,通过调用notify_one()来发送通知,会将处于阻塞状态的等待该条件获得获得信号的线程中的某一个线程(任意一个)恢复执行;notify_all()则是唤醒所有线程。
future
#include<iostream>#include<future>using namespace std;int main(int argc, const char * argv[]){ future<int> f = async([]()->int{ return 42; }); this_thread::sleep_for(chrono::seconds(2)); cout<<f.get()<<endl; return 0;}
future用来获取异步操作的结果。
0 0
- c++ 多线程——c++复习(十)
- C#——多线程
- 复习巩固——C中的指针
- c语言复习 —— 数组
- C语言复习1——基本概念
- C语言——复习函数
- C语言复习——数据类型
- C语言复习——循环结构
- C语言复习——数组、字符串
- C语言复习——函数
- C语言复习——指针
- 数据结构——复习C语言
- C语言——【复习内容提纲】
- C 复习
- C复习
- c复习
- C复习
- 复习C
- 内存测试技巧
- Objc内存管理之MRC
- 架构和框架的区别
- Android 服务器连接工具类HttpUtil
- 吟诗把酒对青春
- c++ 多线程——c++复习(十)
- 昨天的一个披扣的问题处理到很晚没搞定的原因
- tensorflow之扩充自己的图片样本库
- 官方文档
- android的两种网络请求方式关键代码详解
- 性能测试技巧
- 多项式求值
- 国内CVPR和图像处理领域的公司和研究机构
- Java Web中表单数据的获取