C++11开始支持多线程了,之前的多线程编程都需要系统支持,在不同的系统下要用不同的API,使用起来比较复杂,
C++11提供了新头文件<thread> <mutex> <atomic> <future>等支持多线程
在多线程中使用引用容易造成混乱。下面的例子稍显复杂一下,用数组创建多个子线程,并用get_id()方法来获取当前线程的id
可以通过sleep_for让进程睡眠一段时间
由于t1睡眠时间较长,所以t2先执行
C++11提供了新头文件<thread> <mutex> <atomic> <future>等支持多线程
简单的C++11多线程例子
#include <thread>
#include <iostream>
#include <string>
using namespace std;
void f(string name)
{
cout << "hello " << name << endl;
}
int main()
{
thread t(f, "maHuaTeng"); //第一个参数是线程函数,第二个参数是个可变参数,用于传递线程函数参数
t.join(); //join()方法阻塞父线程,直到t线程结束为止
cout << "main" << endl;
system("pause");
return 0;
}
C++11支持Lambda表达式,因此一个新线程的回调函数也可以是有一个Lambda表达式的形式,但是注意如果使用Lambda表达式最好不要使用引用的方式,应该使用值传递的方式来访问数据,
在多线程中使用引用容易造成混乱。下面的例子稍显复杂一下,用数组创建多个子线程,并用get_id()方法来获取当前线程的id
#include <thread>
#include <vector>
#include <string>
#include <iostream>
#include <mutex>
using namespace std;
int main()
{
vector<thread> vec;
mutex m;
for(int i = 0; i < 5; i++)
{
/*thread t([](string name){
cout << "hello" << name << "Thread id" << this_thread::get_id() << endl;
}, "wangDong");*/
vec.push_back(t);
线程对象不能被复制,所以将t添加到vec中会出现编译错误,只能用下面的方式添加到vec中
vec.push_back(thread([&m](string name){ //[]中用来放置互斥锁等,如果没有可以空着,试着把&m去掉跟m.lock(), m.unlock()注释掉,屏幕输出不会跟预期的一样
m.lock();
cout << "hello" << name << "Thread id " << this_thread::get_id() << endl;
m.unlock();
}, "wangDong"));
}
for(auto & a:vec) //auto:用来声明自动变量,a的类型与给a初值类型相同,auto类型变量必须被赋初值以明确变量类型
{
a.join();
}
cout << "main Thread/t" << this_thread::get_id() << endl;
system("pause");
return 0;
}
可以通过sleep_for让进程睡眠一段时间
#include <thread>
#include <mutex>
#include <iostream>
using namespace std;
int main()
{
mutex m;
thread t1([&](){
this_thread::sleep_for(chrono::seconds(10));
m.lock();
for(int i = 0; i < 10; i++)
cout << "thread t1" << endl;
m.unlock();
});
thread t2([&](){
this_thread::sleep_for(chrono::seconds(1));
m.lock();
for(int i = 0; i < 10; i++)
cout << "thread t2" << endl;
m.unlock();
});
t1.join();
t2.join();
cout << "main thread" << endl;
system("pause");
return 0;
}
由于t1睡眠时间较长,所以t2先执行