#include <Windows.h>
#include <future>
#include <chrono>
// working thread
uint32_t waitTime(uint32_t time) {
Sleep(time);
return 0;
}
int main()
{
std::chrono::milliseconds span(10000); // timeout 10s
std::future<uint32_t> future = std::async(waitTime, 5000); // create thread and work for 5s
// three thread status: ready, timeout, deferred
while (future.wait_for(span) == std::future_status::timeout) { // wait for timeout and check thread status
printf("timeout!!\n"); // report timeout and kill thread
}
uint32_t status = future.get(); // get result no matter success or not
printf("status: %d\n", status);
return 0;
}
C++ 设置等待超时功能
于 2022-10-26 20:39:36 首次发布