C++ 线程睡眠(阻塞)

概括

C++ 11中,使用<this_thread>库和 <chrono> 库实现线程睡眠(暂停)。主要使用std::this_thread::sleep_for()std::this_thread::sleep_until()两个函数。
关于<chrono>库请阅读链接

使用示例

使用 std::this_thread::sleep_for

#include <iostream>  
#include <thread>  
#include <chrono>  
  
int main() {  
    std::cout << "线程开始执行...\n";  
  
    // 暂停当前线程2秒  
    std::this_thread::sleep_for(std::chrono::seconds(2));  
  
    std::cout << "线程恢复执行...\n";  
  
    return 0;  
}

使用`std::this_thread::sleep_until

std::this_thread::sleep_until函数使线程暂停,直到指定的时间点。

#include <iostream>  
#include <thread>  
#include <chrono>  
  
int main() {  
    std::cout << "线程开始执行...\n";  
  
    // 获取当前时间并加上2秒  
    auto next_time = std::chrono::system_clock::now() + std::chrono::seconds(2);  
  
    // 暂停当前线程直到next_time  
    std::this_thread::sleep_until(next_time);  
  
    std::cout << "线程恢复执行...\n";  
  
    return 0;  
}

区别

  • sleep_for是睡眠一个时间段
  • sleep_until是睡眠到某一个时间点
  • 两者会使当前线程暂停执行,但不会释放它所占用的资源(如CPU时间片)。
  • 两者与我们熟知的sleep()有一定区别,同时sleep()在不同平台也有不同之处。在Windows的<windows.h>库中,Sleep()接受一个毫秒数作为参数,并导致调用线程暂停执行指定的时间。它是线程级别的,仅影响调用它的线程。在Linux的<unistd.h>中,sleep()函数接受一个无符号整数参数,表示程序要暂停执行的秒数。它是进程级别的,并且会暂停整个进程的执行,而不仅仅是调用它的线程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一直在找资料的菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值