c++线程等待一定时间

#include <iostream>             // std::cout
#include <future>               // std::async, std::future
#include <chrono>               // std::chrono::milliseconds
#include <ctime>
// a non-optimized way of checking for prime numbers:
bool is_prime(int x)
{
    for (int i = 2; i < x; ++i)
        if (x % i == 0)
            return false;
    
    this_thread::sleep_for(chrono::milliseconds(100000));//阻塞当前线程10000毫秒
    return true;
}

int main()
{
    // call function asynchronously:
    std::future < bool > fut = std::async(is_prime, 444444443);

    // do something while waiting for function to set future:
    std::cout << "checking, please wait";
    
    std::chrono::milliseconds span(30000);
    chrono::system_clock::time_point timePoint = chrono::system_clock::now();//stl库获取当前时间
    
   
    while (fut.wait_for(span) == std::future_status::timeout) {
        std::cout << '.';
        break;
    }
        
    chrono::system_clock::time_point timePoint1 = chrono::system_clock::now();//stl库获取当前时间
    std::cout << "value is: " << chrono::duration_cast<chrono::milliseconds>(timePoint1 - timePoint).count() << std::endl;
   
    bool x = fut.get();         // retrieve return value
    chrono::system_clock::time_point timePoint2 = chrono::system_clock::now();//stl库获取当前时间
    std::cout << "value1 is: " << chrono::duration_cast<chrono::milliseconds>(timePoint2 - timePoint1).count() << std::endl;

    std::cout << "444444443 " << (x ? "is" : "is not") << " prime.\n";

    return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值