C++中是否有可被事件提前唤醒的Sleep类替代函数?
C++ 线程可中断延迟的实现方案
原生标准库是否有直接函数?
C++标准库中没有直接提供这种既能指定时长暂停、又能被外部事件中断的函数。std::this_thread::sleep_for或sleep_until只能固定等待时长,无法被主动唤醒。
可行解决方案
1. 使用条件变量(推荐)
利用std::condition_variable配合互斥锁,实现可唤醒的延迟等待。核心逻辑是:线程等待条件变量,超时时间设为指定时长;当外部事件触发时,通知条件变量唤醒线程。
示例代码:
#include <thread> #include <condition_variable> #include <mutex> std::condition_variable cv; std::mutex mtx; bool stop_flag = false; void wait_with_interrupt(std::chrono::milliseconds duration) { std::unique_lock<std::mutex> lock(mtx); cv.wait_for(lock, duration, []{ return stop_flag; }); stop_flag = false; } void trigger_interrupt() { std::lock_guard<std::mutex> lock(mtx); stop_flag = true; cv.notify_one(); }
2. 优化版原子变量轮询(类似你的自定义Timer)
你的自定义Timer思路可行,但存在忙等占用CPU的问题,优化后可降低资源消耗:
#include <chrono> #include <thread> #include <atomic> float Timer(std::chrono::milliseconds duration, std::atomic<bool>& stop) { auto start = std::chrono::steady_clock::now(); std::chrono::milliseconds elapsed; while ((elapsed = std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::steady_clock::now() - start)) <= duration) { if (stop.load()) { return elapsed.count() / 1000.f; } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return 0.f; }
注意:用std::atomic<bool>替代普通bool,避免多线程竞争导致的未定义行为。
3. 使用信号量(C++20及以上)
C++20引入的std::counting_semaphore可实现类似功能:
#include <thread> #include <semaphore> std::counting_semaphore<1> sem(0); void wait_with_interrupt(std::chrono::milliseconds duration) { sem.try_acquire_for(duration); } void trigger_interrupt() { sem.release(); }
对你的自定义Timer的点评
你的实现思路正确,但存在三个问题:
clock()统计的是CPU时间,不是实际流逝的挂钟时间,线程被调度出去时计时会不准确,建议改用std::chrono::steady_clock。- 普通bool不具备线程安全性,多线程读写会有竞争,必须用
std::atomic<bool>保证原子操作。 - 无休眠的忙等会持续占用CPU资源,添加短睡眠可有效缓解。
内容的提问来源于stack exchange,提问作者Александр
相关产品推荐
相关产品推荐

