C++线程的锁

本文通过一个具体的C++多线程实例,详细解释了在多线程环境中使用锁来解决数据竞争问题的重要性。文章首先展示了无锁情况下线程同步失败的问题,然后介绍了如何手动添加和释放锁,最后探讨了C++提供的更便捷的锁使用方式。

C++不加锁的多线程实例

#include <iostream>
#include <thread>

using namespace std;


int num = 100;

void fun1() {
	if (num > 0) {
		num = num - 1;
		this_thread::sleep_for(chrono::milliseconds(10));
		printf("the num=%d\n", num);
	}
	else
	{
		printf("the num = 0");
	}
}

int main() {
	thread threads[20];
	for (int i=0;i<20;i++)
	{
		threads[i]= thread(fun1);
	}
	cout << "main thread" << endl;
	for (int i=0; i<20; i++)
	{
		threads[i].join();
	}
	return 0;
}

显示的结果如下:

结果输出全是80,不符合需求。需要在线程的具体方法中添加锁,代码如下:

#include <iostream>
#include <thread>
#include <mutex>

using namespace std;


int num = 100;
mutex mu;

void fun1() {
	mu.lock();	//手动加锁
	if (num > 0) {
		num = num - 1;
		this_thread::sleep_for(chrono::milliseconds(10));
		printf("the num=%d\n", num);
	}
	else
	{
		printf("the num = 0");
	}
	mu.unlock();	//手动解锁
}

int main() {
	thread threads[20];
	for (int i=0;i<20;i++)
	{
		threads[i]= thread(fun1);
	}
	cout << "main thread" << endl;
	for (int i=0; i<20; i++)
	{
		threads[i].join();
	}
	return 0;
}

除了手动加锁和解锁外,C++也为我们提供了更便捷的使用方式:

lock_guard<mutex> lock(mu);	//当前函数结束,会自动释放锁
#include <mutex>
recursive_mutex mut;	//同一个线程可以多次添加锁

//不推荐使用,一旦爆发问题,很难修复。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值