温馨提示×

c++ wait_for如何运行

c++
小樊
93
2024-11-24 12:09:50
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

wait_for是C++标准库 <chrono><thread> 中的一个函数,它用于等待一个给定的时间间隔或者直到某个条件成立

#include <iostream>
#include <chrono>
#include <thread>

int main() {
    std::cout << "Starting...\n";

    // 等待1秒
    std::this_thread::sleep_for(std::chrono::seconds(1));

    std::cout << "1 second has passed...\n";

    // 等待直到某个条件成立(例如,当前时间大于某个特定值)
    auto start = std::chrono::steady_clock::now();
    while (std::chrono::steady_clock::now() - start < std::chrono::seconds(2)) {
        // 检查条件是否满足
        if (/* your condition here */) {
            break;
        }

        // 如果没有满足条件,继续等待一段时间
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    std::cout << "Condition met or 2 seconds have passed...\n";

    return 0;
}

在这个示例中,wait_for函数用于等待1秒。你可以根据需要修改时间间隔和条件。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++ wait_for怎样发挥

0