C++ 线程暂停与恢复:使用 sleep_for 和 条件变量
在 C++ 中,可以使用标准库中的 <thread> 头文件中的 sleep_for() 函数来实现线程暂停功能。该函数可以让线程休眠指定的时间,单位为毫秒。例如,以下代码可以让当前线程休眠 1 秒钟:
#include <chrono>
#include <thread>
std::this_thread::sleep_for(std::chrono::seconds(1));
如果要实现线程马上恢复的功能,可以使用条件变量 (std::condition_variable) 和互斥锁 (std::mutex) 来实现。具体实现过程如下:
-
在线程函数中,使用互斥锁锁住某个变量,表示线程需要等待某个条件满足才能继续执行。
-
在主线程中,修改该变量的值,然后通知等待该条件的线程。
-
等待线程收到通知后,解锁互斥锁并继续执行。
以下是一个简单的示例代码:
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
void thread_func() {
std::unique_lock<std::mutex> lock(mtx);
while (!ready) {
cv.wait(lock);
}
// do something
}
int main() {
std::thread t(thread_func);
// do something
{
std::lock_guard<std::mutex> lock(mtx);
ready = true;
}
cv.notify_one();
// do something
t.join();
return 0;
}
在上面的代码中,线程函数 thread_func() 会在 while 循环中等待 ready 变量的值变为 true,表示条件已经满足。在主线程中,通过修改 ready 变量的值并调用 cv.notify_one() 函数来通知等待线程。等待线程收到通知后,会解锁互斥锁并继续执行。
原文地址: https://www.cveoy.top/t/topic/jnSb 著作权归作者所有。请勿转载和采集!