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 分钟前
【C++】constexpr动态内存与双模式革命
开发语言·c++
云深处@18 分钟前
【C++】哈希表
开发语言·c++
weixin_4521595521 分钟前
模板编译期条件分支
开发语言·c++·算法
啊我不会诶22 分钟前
蓝桥杯练习 混乱的数组
c++·蓝桥杯
2501_9411481525 分钟前
C++ map / multimap 保姆级教程
java·开发语言·c++
GHL28427109030 分钟前
TeamTalk-msg_server学习
运维·服务器·c++·学习
ʚB҉L҉A҉C҉K҉.҉基҉德҉^҉大34 分钟前
C++中的策略模式进阶
开发语言·c++·算法
Zach_yuan1 小时前
C++ Lambda 表达式从入门到进阶
开发语言·c++
郝学胜-神的一滴1 小时前
Linux网络编程之Socket函数:构建通信的桥梁
linux·服务器·网络·c++·程序人生
weixin_445402301 小时前
模板元编程应用场景
开发语言·c++·算法