C++ Concurrency in Action 2nd

书籍地址:

https://www.bookstack.cn/read/CPP-Concurrency-In-Action-2ed-2019/content-about_this_book-chinese.md

 

  1. 你好,C++的并发世界

*并发:单个系统里同时执行多个独立地任务,而非顺序的进行一些活动。

*分离关注点(SOC) Separation of concerns

 + 一是分层,二是面向接口编程

*native_handle():直接操作底层实现

 

 

  1. 线程管理

*detach过的线程为 守护线程

*发后即忘(fire and forget)的任务使用到守护进程方式(detach函数)。

* void process_big_object(std::unique_ptr<big_object>);

std::unique_ptr<big_object> p(new big_object);

p->prepare_data(42);

std::thread t(process_big_object, std::move(p));

 

*scoped_thread 用法

  1. class scoped_thread
  2. {
  3. std::thread t;
  4. public:
  5. explicit scoped_thread(std::thread t_): // 1
  6. t(std::move(t_))
  7. {
  8. if(!t.joinable()) // 2
  9. throw std::logic_error(“No thread”);
  10. }
  11. ~scoped_thread()
  12. {
  13. t.join(); // 3
  14. }
  15. scoped_thread(scoped_thread const&)=delete;
  16. scoped_thread& operator=(scoped_thread const&)=delete;
  17. };
  18.  
  19. struct func; // 定义在清单2.1中
  20.  
  21. void f()
  22. {
  23. int some_local_state;
  24. scoped_thread t(std::thread(func(some_local_state))); // 4
  25. do_something_in_current_thread();
  26. } // 5

 

*std::thread::hardware_concurrency()  返回 cpu核心数量

*std::this_thread::get_id() ;  t1.get_id();  返回线程id

 

 

  1. 线程间共享数据

*互斥量:std::mutex    lock(), unlock()操作

 

*std::lock_guard<std::mutex>  guard(some_mutex);  来保证正确解锁

+  C++17版本简化为: std::lock_guard guard(some_mutex);

+ 加强版数据保护机制:std::scoped_lock guard(some_mutex);            

 

*返回指向弹出值的指针时,使用 std::shared_ptr

 

*std::lock: 一次性锁住多个互斥量,避免死锁

举例:

void swap(X& lhs, X& rhs)

{

if (&lhs == &rhs)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值