多线程——thread库

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、多线程同步 

 线程安全问题是指多个线程并发/并行的访问/修改共享资源的数据,从而造成的数据混乱的问题。

2.1 mutex

2.2 atomic原子性操作 

2.3 condition_variable条件变量

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值