zoukankan      html  css  js  c++  java
  • std::lock_guard和std::mutex 的用法

    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;
    }
    
  • 相关阅读:
    ASP.NET Core 2.2 基础知识(二) 中间件
    ASP.NET Core 2.2 基础知识(一) 依赖注入
    初识.NET Core
    volatile 和 Interlocked
    线程池
    MySQL 将某个字段值的记录排在最后,其余记录单独排序
    MySQL 一张表中两个字段值互换
    (转) C#解惑:HashSet<T>类
    利用 ildasm 修改被编译后DLL文件
    shell 字符串判断
  • 原文地址:https://www.cnblogs.com/joyer/p/15668695.html
Copyright © 2011-2022 走看看