内容纲要
blog: C++并发编程读书笔记 · 语雀 (yuque.com)
第2章 线程管理
2.1节 Basic thread management 线程管理的基础
#include <iostream>
#include <thread>
class background_task
{
public:
void operator()()
{
do_something();
do_something_else();
}
void do_something()
{
std::cout<<"do_something"<<std::endl;
}
void do_something_else()
{
std::cout << "do_something_else" << std::endl;
}
};
int main()
{
std::thread my_thread(background_task());
std::cout << "Hello World!\n";
return 0;
}
std::thread my_thread(background_task());这一句代码,你以为构造的是一个临时对象传入到thread里面,然而编译时,会提示:
“warning C4930: ‘std::thread my_thread(background_task (__cdecl *)(void))’: prototyped function not called (was a variable definition intended?)”
原因是:这行代码,声明的是一个返回值为std::thread,然后它有一个参数,这个参数是一个函数指针,函数指针的返回值是class background_task。
2.4节 Choosing the number of threads at runtime 运行时决定线程数量
std::thread::hardware_concurrency()可以获取硬件的线程数,当然也可能返回0。
void OutputHardwareThreadNum()
{
// 获取可以并发的线程数
// 本机输出:thread num is :16
// 也有可能是0
std::cout << "thread num is :" << std::thread::hardware_concurrency() << std::endl;
}
2.5 Identifying threads 标识线程
使用std::thread::id来标识是哪条线程。
1、线程中,使用std::this_thread::get_id() ,获得自己的线程ID
2、如果有thread线程对象,使用成员函数thread::get_id()来获取线程ID
第3章 线程间共享数据
3.2 Protecting shared data with mutexes 使用互斥量保护共享数据
使用std::mutex创建互斥量
上锁的方法,C++17使用std::scoped_lock,C++17以下版本使用std::lock_guard加锁