C++11 并发实战阅读笔记(2)
来源:互联网 发布:ip交换网络拓扑的设计 编辑:程序博客网 时间:2024/05/16 05:03
第三章
#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锁住,不能只锁单一的一个函数!
0 0
- C++11 并发实战阅读笔记(2)
- C++11 并发实战阅读笔记(1)
- java并发实战阅读笔记 --2
- Linux C 编程实战--阅读笔记
- java并发编程实战阅读笔记(第二章)线程安全性
- java并发编程实战阅读笔记(第三章)对象的共享
- java并发编程实战阅读笔记(第四章)对象的组合
- java并发实战阅读笔记 --1
- 关于《Java并发编程实战》 -- 第一部分的阅读笔记
- 关于《Java并发编程实战》 -- 第二部分的阅读笔记
- 《Java并发编程实战》- 个人阅读总结(一)
- Java并发编程实战笔记(2)- ConcurrentHashMap
- 《java并发编程实战》笔记(1-2)
- 《C Primer Plus》阅读笔记(2)
- 《Maven实战》阅读笔记整理(一)
- 《Maven实战》阅读笔记整理(二)
- 《Maven实战》阅读笔记整理(三)
- 《Maven实战》阅读笔记(四)
- SCI论文从入门到精通
- IOS:dispatch_group_enter的学习
- 卫星导航术语 -- 词汇与概念解释(200条)(转自今日北斗)
- Android blueZ HCI(一):hciconfig实现及常用方法
- URI,URN,URL三者的关系
- C++11 并发实战阅读笔记(2)
- 让apache支持CGI
- having与group by
- 设计模式之迭代器模式
- Visual Studio系列 卸载visual assist插件和vmware debugger插件的方法
- 累【非技术贴】
- Shell教程(四):条件语句、循环语句、break/continue
- CSS文件动态加载
- hive笔记