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

相关推荐
旖-旎3 分钟前
哈希表(字母异位次分组)(5)
数据结构·c++·算法·leetcode·哈希算法·散列表
无限进步_21 分钟前
【C++】多重继承中的虚表布局分析:D类对象为何有两个虚表?
开发语言·c++·ide·windows·git·算法·visual studio
特立独行的猫a1 小时前
OpenHarmony平台移植 gifsicle:C/C++ 三方库适配实践(Lycium / tpc_c_cplusplus)
c语言·c++·harmonyos·openharmony·三方库适配·lycium
hello world 9991 小时前
Cursor开发实战应用
c++·ai编程·cursor
kyle~1 小时前
工程数学---Eigen库(C++唯一标配线性代数库)
开发语言·c++·线性代数
fish_xk1 小时前
c++中的模板
c++·模板
CoderCodingNo1 小时前
【GESP】C++五、六级练习题 luogu-P1886 【模板】单调队列 / 滑动窗口
开发语言·c++·算法
paeamecium2 小时前
【PAT甲级真题】- All Roads Lead to Rome (30)
数据结构·c++·算法·pat考试·pat
John.Lewis2 小时前
C++进阶(6)C++11(2)
开发语言·c++·笔记
Mapleay2 小时前
CLion IDE 使用
c++