C++11 并发实战阅读笔记(2)

本文探讨了在C++中实现线程安全的具体方法,包括使用`std::mutex`来保护共享数据,并通过`std::lock_guard`实现资源获取即初始化(RAII)模式。此外还介绍了如何为栈结构实现线程安全操作。

第三章


#include <list>
#include <mutex>
#include <algorithm>
std::list<int> some_list;
std::mutex some_mutex;
void add_to_list(int new_value)
{
   std::lock_guard<std::mutex> guard(some_mutex);   // std::lock_guard 是RAII用法
   some_list.push_back(new_value);
}
bool list_contains(int value_to_find)
{
   std::lock_guard<std::mutex> guard(some_mutex);
   return std::find(some_list.begin(),some_list.end(),value_to_find)
   != some_list.end();
}
上面没啥好讲的。。常规用法,就是用了一个RAII


class some_data
{
  int a;
  std::string b;
  public:
  void do_something();
};
class data_wrapper
{
  private:
  some_data data;
  std::mutex m;
  public:
  template<typename Function>
  void process_data(Function func)
  {
    std::lock_guard<std::mutex> l(m);
    func(data);
  }
  };
some_data* unprotected;
void malicious_function(some_data& protected_data)
{
  unprotected=&protected_data;
}
data_wrapper x;
void foo()
{
  x.process_data(malicious_function);
  unprotected->do_something();
}
不要在使用了mutex保护的函数返回引用或者指针,这样会使数据失去保护: 
unprotected->do_something();  // 这样就在mutex保护之外访问了数据



#include <exception>
#include <memory>
#include <mutex>
#include <stack>
struct empty_stack: std::exception
{
  const char* what() const throw();
};
template<typename T>
class threadsafe_stack
{
  private:
  std::stack<T> data;
  mutable std::mutex m;
  public:
  threadsafe_stack(){}
  threadsafe_stack(const threadsafe_stack& other)
  {
    std::lock_guard<std::mutex> lock(other.m);
    data=other.data;
  }
  threadsafe_stack& operator=(const threadsafe_stack&) = delete;
  void push(T new_value)
  {
    std::lock_guard<std::mutex> lock(m);
    data.push(new_value);
  }
  std::shared_ptr<T> pop()
  {
    std::lock_guard<std::mutex> lock(m);
    if(data.empty()) throw empty_stack();
    std::shared_ptr<T> const res(std::make_shared<T>(data.top()));
    data.pop();
    return res;
  }
  void pop(T& value)
  {
    std::lock_guard<std::mutex> lock(m);
    if(data.empty()) throw empty_stack();
    value=data.top();
    data.pop();
  }
  bool empty() const
  {
    std::lock_guard<std::mutex> lock(m);
    return data.empty();
  }
};

这一段书上讲的有点啰嗦,其实按照我自己的理解就是,对stack的所有操作,尤其是连续的操作都必须用mutex锁住,不能只锁单一的一个函数!





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值