C++ 线程 (3)

一、Wait functions(等待函数)

1. wait

作用:阻塞线程,直到被唤醒(或谓词满足)。

cpp 复制代码
// 重载1:仅等待唤醒
void wait(std::unique_lock<std::mutex>& lock);

// 重载2:等待"唤醒 且 谓词pred返回true"(避免虚假唤醒)
template< class Predicate >
void wait(std::unique_lock<std::mutex>& lock, Predicate pred);

参数:

lock:std::unique_lock<std::mutex> 的引用(调用时需已持有锁);

pred:可调用对象(函数 /lambda 等),返回bool(表示等待的条件)。

返回值:无(void)。

2. wait_for

作用:阻塞线程指定时间段,超时 / 被唤醒时返回。

cpp 复制代码
// 重载1:等待时间段rel_time,返回等待状态
template< class Rep, class Period >
std::cv_status wait_for(
    std::unique_lock<std::mutex>& lock,
    const std::chrono::duration<Rep, Period>& rel_time
);

// 重载2:等待"时间段内被唤醒 且 pred返回true",返回pred的结果
template< class Rep, class Period, class Predicate >
bool wait_for(
    std::unique_lock<std::mutex>& lock,
    const std::chrono::duration<Rep, Period>& rel_time,
    Predicate pred
);

参数:

lock:同wait。

rel_time:等待的最大时间(如std::chrono::seconds(2))。

pred:同wait。

返回值:

无条件版本:std::cv_status::timeout(超时)或std::cv_status::no_timeout(被唤醒)。

带谓词版本:pred()的结果(超时则返回false)。

3. wait_until

cpp 复制代码
// 无条件限时等待
template <class Clock, class Duration>
std::cv_status wait_until(std::unique_lock<std::mutex>& lock, 
                          const std::chrono::time_point<Clock, Duration>& abs_time);

// 带谓词
template <class Clock, class Duration, class Predicate>
bool wait_until(std::unique_lock<std::mutex>& lock, 
                const std::chrono::time_point<Clock, Duration>& abs_time, 
                Predicate pred);

功能:限时等待(指定绝对时间点),到达时间点或被唤醒后返回。

参数:

lock:同wait。

abs_time:等待的截止时间点(如std::chrono::system_clock::now() + std::chrono::seconds(2))。

pred:同wait。

返回值:

无条件版本:std::cv_status::timeout(超时)或std::cv_status::no_timeout(被唤醒)。

带谓词版本:pred()的结果(超时则返回false)。

二、Notify functions(通知函数)

1. notify_one

功能:唤醒一个等待在当前条件变量上的线程(若存在)。

cpp 复制代码
void notify_one() noexcept;

参数:无。

返回值:无(void)。

2. notify_all

cpp 复制代码
void notify_all() noexcept;

功能:唤醒所有等待在当前条件变量上的线程。

参数:无。

返回值:无(void)。

相关推荐
炸膛坦客4 小时前
单片机/C/C++八股:(二十六)IIC 专题(I²C)---- 上集
c语言·c++·单片机
旖-旎4 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
Henry Zhu1235 小时前
C++中的特殊成员函数与智能指针
c++
_wyt0017 小时前
多重背包问题详解
c++·背包dp
Ljwuhe8 小时前
C++——多态
开发语言·c++
越甲八千9 小时前
STL stack为何没有迭代器
c++
从零开始的代码生活_10 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸10 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
GIS阵地11 小时前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
王维同学11 小时前
[原创][Windows C++]LSA 认证、安全与通知包的注册表枚举
c++·windows·安全