书籍地址:
https://www.bookstack.cn/read/CPP-Concurrency-In-Action-2ed-2019/content-about_this_book-chinese.md
- 你好,C++的并发世界
*并发:单个系统里同时执行多个独立地任务,而非顺序的进行一些活动。
*分离关注点(SOC) Separation of concerns
+ 一是分层,二是面向接口编程
*native_handle():直接操作底层实现
- 线程管理
*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 用法
- class scoped_thread
- {
- std::thread t;
- public:
- explicit scoped_thread(std::thread t_): // 1
- t(std::move(t_))
- {
- if(!t.joinable()) // 2
- throw std::logic_error(“No thread”);
- }
- ~scoped_thread()
- {
- t.join(); // 3
- }
- scoped_thread(scoped_thread const&)=delete;
- scoped_thread& operator=(scoped_thread const&)=delete;
- };
- struct func; // 定义在清单2.1中
- void f()
- {
- int some_local_state;
- scoped_thread t(std::thread(func(some_local_state))); // 4
- do_something_in_current_thread();
- } // 5
*std::thread::hardware_concurrency() 返回 cpu核心数量
*std::this_thread::get_id() ; t1.get_id(); 返回线程id
- 线程间共享数据
*互斥量: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)
return;