1、thread库
C++11线程库的基本使用,包括创建线程、启动线程、等待线程完成、分离线程
#include<iostream>
#include<thread>
using namespace std;
void printFun1(string msg)
{
cout << msg << endl;
}
void printFun2(int num)
{
cout << msg << endl;
}
int main()
{
string str = "Hello World";
thread myThread1(printFun1, str); //创建线程
if(myThread1.joinable){
myThread1.join(); //等待线程执行完毕,主线程再继续执行
}
int num = 2;
thread myThread2(printFun2, num); //创建线程
if(myThread2.joinable){
myThread2.detach(); //分离线程, 若主线程先执行完毕,子线程在后台持续运行
}
return 0;
}
线程函数的参数是以值拷贝的方式拷贝到线程栈空间中的,因此即使线程参数为引用类型,在线程中修改后也不能修改外部实参,因为其实际引用的是线程栈中的拷贝,而不是外部实参。
如果想通过形参修改外部实参,可采用1)std::ref()函数 ;2)指针传递
void ThreadFunc1(int& x) { x += 10; }
void ThreadFunc2(int* x) { *x += 10; }
int main()
{
int a = 10;
//在线程函数中对a修改,不会影响外部实参
//并且这里会发生int与int&类型不匹配的报错
//thread t1(ThreadFunc1, a);
//t1.join();
//cout << a << endl;
//如果想要通过形参改变外部实参时,必须借助std::ref()函数
thread t2(ThreadFunc1, std::ref(a));
t2.join();
cout << a << endl; // 输出a=20
//其实现原理类似于地址的拷贝
thread t3(ThreadFunc2, &a);
t3.join();
cout << a << endl; // 输出a=30
return 0;
}
2、多线程同步
线程安全问题是指多个线程并发/并行的访问/修改共享资源的数据,从而造成的数据混乱的问题。