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)。

相关推荐
肆忆_8 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星12 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马4 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc4 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
问好眼4 天前
《算法竞赛进阶指南》0x01 位运算-3.64位整数乘法
c++·算法·位运算·信息学奥赛