Jason的菜地
谁言书生无用,笔下自有乾坤

std::lock_guard和std::mutex 的用法

功能介绍

二者均属于C++11的特性:

  • std::mutex属于C++11中对操作系统锁的最常用的一种封装,可以通过lock、unlock等接口实现对数据的锁定保护。

  • std::lock_guard是C++11提供的锁管理器,可以管理std::mutex,也可以管理其他常见类型的锁。

    std::lock_guard的对锁的管理属于RAII风格用法(Resource Acquisition Is Initialization),在构造函数中自动绑定它的互斥体并加锁,在析构函数中解锁,大大减少了死锁的风险。

代码示例

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

int loop_cnt = 10000000;

class Widget
{
public:
	Widget() = default;
	~Widget() = default;

	void addCnt()
	{
		std::lock_guard<std::mutex> cLockGurad(lock_); //构造时加锁,析构时解锁

		// lock_.lock(); //不使用lock_guard时的写法
		cnt++;
		// lock_.unlock();//不使用lock_guard时的写法,万一没有解锁就会死锁。
	}

	int cnt = 0;

private:
	std::mutex lock_;
};

void ThreadMain1(Widget *pw)
{
	std::cout << "thread 1 begin." << "\n";
	for (int i = 0; i < loop_cnt; i++)
		pw->addCnt();
	std::cout << "thread 1 end."  << "\n";
}

void ThreadMain2(Widget *pw)
{
	std::cout << "thread 2 begin."  << "\n";
	for (int i = 0; i < loop_cnt; i++)
		pw->addCnt();
	std::cout << "thread 2 end."  << "\n";
}

int main()
{
	Widget *pw = new Widget();

	std::thread t1(&ThreadMain1, pw);
	std::thread t2(&ThreadMain2, pw);

	t1.join();
	t2.join();

	std::cout << "cnt =" << pw->cnt << std::endl;
	
	return 0;
}
posted on 2021-12-09 18:11  贾森  阅读(9549)  评论(0)    收藏  举报