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个线程都执行了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值