c++ 11 std::lock_guard

std::lock_guard 是遵循 RAII

RAII

RAII 介绍

RAII技术被认为是C++中管理资源的最佳方法,进一步引申,使用RAII技术也可以实现安全、简洁的状态管理,编写出优雅的异常安全的代码。

资源管理
RAII是C++的发明者Bjarne Stroustrup提出的概念,RAII全称是“Resource Acquisition is Initialization”,直译过来是“资源获取即初始化”,也就是说在构造函数中申请分配资源,在析构函数中释放资源。因为C++的语言机制保证了,当一个对象创建的时候,自动调用构造函数,当对象超出作用域的时候会自动调用析构函数。所以,在RAII的指导下,我们应该使用类来管理资源,将资源和对象的生命周期绑定。

看一段简单的代码:

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

/* global */
int g_i = 0;
std::mutex g_mutex;


void g_increment()
{
	g_mutex.lock();
	++g_i;
	std::cout <<"thread_id:"<<std::this_thread::get_id() <<",g_i:" << g_i << std::endl;
	
	if(XXX)
		return;

	g_mutex.unlock();
}

int main()
{
	std::cout << "mian g_i:" << g_i << std::endl;

	std::thread threads[10];

	for (auto i = 0; i < 10; i++)
		threads[i] = std::thread(g_increment);

	for (auto &t : threads)
		t.join();

	system("pause");
}

mutex 要手动的 lock 和 unlock
如果 我们上面执行了
if(XXX)
return;
或者有异常执行了 return
那么其他的线程就要排队 等待unlock
比如这样
只有第一个线程执行了 return了 没unlock 后面的线程都在等。
在这里插入图片描述

我们可以用 std::lock_guard 代替

当 离开作用域时会自动的释放, 不用我们在每个地方都写 unlock

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

/* global */
int g_i = 0;
std::mutex g_mutex;


void g_increment()
{
	std::lock_guard<std::mutex> lock(g_mutex);

	++g_i;
	std::cout <<"thread_id:"<<std::this_thread::get_id() <<",g_i:" << g_i << std::endl;
	
	/// 离开作用域就会被释放
}

int main()
{
	std::cout << "mian g_i:" << g_i << std::endl;

	std::thread threads[10];

	for (auto i = 0; i < 10; i++)
		threads[i] = std::thread(g_increment);

	for (auto &t : threads)
		t.join();

	system("pause");
}

在这里插入图片描述
10个线程都执行了

发布了178 篇原创文章 · 获赞 396 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/weixin_42837024/article/details/105047988
今日推荐