C++11多线程

本文介绍了C++11中的多线程特性,包括thread类的使用、this_thread的get_id函数、线程的joinable、join和detach方法、硬件并发数的获取。还讨论了mutex、recursive_mutex、timed_mutex及其相关类如lock_guard和unique_lock的使用。此外,还讲解了condition_variable条件变量以及future类在线程间通信的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++11多线程

class thread

在这里插入图片描述
上图是thread类的成员变量与成员函数。

1、创建一个线程(构造函数)

thread threadname(entrance,**args);

thread是一个类,它的构造函数也比较简单,只需要传入一个入口函数的指针以及入口函数对应的参数。

另一种创建方法(移动赋值构造,“operator=”)

thread threadname = thread(entrance, **args);

2、外部获取线程pid。

从上图可以看到,thread类自带了一个获取线程id(注意不是pid)的成员函数,我们只需要在外部调用就可以了。

(thread::id) tid = threadname.get_id();

不过,这种获取方式只能在外部获取,或者说只能用在定义了threadname的函数中调用,那么如果我希望在执行函数(entrance)中访问当前线程的线程id该如何做呢?

可以这样做:

(thread::id) tid = std::this_thread::get_id()

this_thread是本地类,包含静态成员函数get_id()。可返回本地线程的线程id.

3、joinable、join、detach

这三个函数负责处理线程的销毁工作,join和detach的主要区别在于,join阻塞主进程执行,直到所等待的线程结束。而detach相反,它不会阻塞主进程,任由线程自由终止(detach的释义为“分支,分离”),这种情况下可配合信号一起使用。

4、hardware_concurrency【static】

"""
Returns the number of hardware thread contexts.

The interpretation of this value is system- and implementation- specific, and may not be exact, but just an approximation.

Note that this does not need to match the actual number of processors or cores available in the system: A system can support multiple threads per processing unit, or restrict the access to its resources to the program.
"""

该函数返回的不是准确的CPU个数,而是系统建议的硬件线程个数。这是一个静态函数,也就是说这个函数调用不通过对象调用,而通过类名调用。

(unsigned int) count = thread::hardware_concurrency();
class this_thread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值