c++ 多线程——c++复习(十)
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用来获取异步操作的结果。
posted on 2016-05-12 19:27 hello_vzjw 阅读(119) 评论(0) 收藏 举报
浙公网安备 33010602011771号