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;
    }
    
  • 相关阅读:
    java框架--Spring XML 配置基础(一)
    工具的使用与安装--oracle卸载
    java web--jsp(4)
    java web--JSP(3)
    洛谷 P3384 【模板】轻重链剖分
    洛谷 P1103 书本整理
    洛谷 P1977 出租车拼车
    洛谷 P1129 [ZJOI2007]矩阵游戏
    洛谷 P2319 [HNOI2006]超级英雄
    洛谷 P1640 [SCOI2010]连续攻击游戏
  • 原文地址:https://www.cnblogs.com/joyer/p/15668695.html
Copyright © 2011-2022 走看看