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 小时前
C++ 基础入门完全指南
c++
用户805533698032 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
BadBadBad__AK2 天前
线段树维护区间 k 次方和
c++·数学·算法·stl
卷无止境3 天前
Eigen 库如何借助 OpenMP 加速计算
c++·后端
卷无止境3 天前
OpenMPI、MPICH 与 OpenMP:关系、核心概念与架构全解
c++·后端
郝学胜_神的一滴4 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境6 天前
C++ 的Eigen 库全解析
c++
卷无止境6 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴6 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18008 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝