我没有自己的代码,因为我甚至不知道如何开始,对不起。我找不到任何关于std::ifstream文件读取和如何实现计时器的东西。
我想读取一个电影列表,如果读取这个文件花费的时间超过5分钟,我希望它停止并std::cout它花费的时间太长。如何在std::fstream中实现计时器
发布于 2018-05-09 03:22:01
您可以使用std::async。它返回一个future对象,您可以在该对象上wait_for指定的最大时间间隔。
std::ifstream file;
auto f = std::async(std::launch::async, [&file]{ file.open("path/to/file"); });
auto status = future.wait_for(std::chrono::minutes(5));
if (status == std::future_status::timeout) {
std::cout << "timeout\n";
return 1;
} std::launch::async表示将使用新线程。
发布于 2018-05-09 05:59:44
考虑在不使用计时器的情况下解决问题。
从记录当前时间开始。然后逐块读取文件块(即,不是在单个调用中,而是通过一个循环读取其中的一部分)。对于每个块,处理它,然后检查相对于开始的运行时间。如果它超过了你的门槛,就退出。
在伪代码中:
t0 = time();
for (;;) {
chunk = read();
if (eof)
success();
process(chunk);
t = time();
if (t - t0 > timeout)
error();
}https://stackoverflow.com/questions/50240829
复制相似问题