#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;
}
c++线程等待一定时间
最新推荐文章于 2024-07-04 22:52:27 发布