c++ 线程休眠与唤醒
在多线程程序开发中,有时我们需要让线程在某处休眠一段时间,或者在某处唤醒一个线程。C++标准库中提供了一些方法来实现线程的休眠和唤醒。
线程休眠
在C++中,要让一个线程休眠一段时间,最简单的方法是使用std::this_thread::sleep_for
函数。该函数定义在<thread>
头文件中,用于让当前线程休眠指定的时间段。
下面是一个简单的示例,演示如何让线程休眠3秒钟:
#include <iostream>
#include <thread>
#include <chrono>
void sleep_thread()
{
// 休眠3秒钟
std::this_thread::sleep_for(std::chrono::seconds(3));
std::cout << "Thread woke up after 3 seconds." << std::endl;
}
int main()
{
std::thread t(sleep_thread); // 启动线程
t.join(); // 等待线程结束
return 0;
}
在上面的示例中,我们定义了一个sleep_thread
函数,该函数通过调用std::this_thread::sleep_for
函数来让线程休眠3秒钟。在main
函数中,我们创建了一个新线程,并让其执行sleep_thread
函数。线程将在调用std::this_thread::sleep_for
函数之后休眠3秒钟,然后继续执行打印语句。
线程唤醒
有时候我们需要唤醒一个休眠中的线程,C++标准库中提供了std::condition_variable
类和std::mutex
类来实现线程的唤醒。
下面是一个示例,演示如何使用std::condition_variable
和std::mutex
来唤醒一个线程:
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
std::condition_variable cv;
std::mutex mtx;
bool ready = false;
void wait_thread()
{
std::unique_lock<std::mutex> lk(mtx);
cv.wait(lk, []{ return ready; });
std::cout << "Thread is awake." << std::endl;
}
int main()
{
std::thread t(wait_thread); // 启动线程
// 休眠1秒钟
std::this_thread::sleep_for(std::chrono::seconds(1));
{
std::lock_guard<std::mutex> lk(mtx);
ready = true;
}
cv.notify_one();
t.join(); // 等待线程结束
return 0;
}
在上面的示例中,我们创建了一个std::condition_variable
对象cv
和一个std::mutex
对象mtx
,以及一个标志变量ready
,用于控制线程是否唤醒。我们定义了一个wait_thread
函数,该函数在一个std::unique_lock
对象上调用cv.wait
函数等待ready
变为true
。在main
函数中,我们创建了一个新线程,并让其执行wait_thread
函数。然后,我们休眠1秒钟,并在一个std::lock_guard
对象上修改ready
为true
,并调用cv.notify_one
函数唤醒等待中的线程。
总结
通过使用std::this_thread::sleep_for
函数和std::condition_variable
类,我们可以很方便地在C++中实现线程的休眠和唤醒。这些方法可以帮助我们更好地控制线程的执行顺序,提高多线程程序的效率。当我们需要让线程在某处休眠一段时间,或者在某处唤醒一个线程时,可以灵活运用这些方法。