C++ 设置等待超时功能

#include 
#include 
#include 

// 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++,Primer,c++,开发语言,算法)