gpt4 book ai didi

c++ - 如何在 C++ 中读取最多 X 秒?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:18:28 24 4
gpt4 key购买 nike

我希望我的程序等待读取 FIFO 中的内容,但是如果 read(我使用 std::fstream)持续超过 5 秒,我想要它退出。

有可能还是我必须绝对使用alarm

谢谢。

最佳答案

我不相信有一个干净的方法来完成这个,即仅可移植的 C++ 解决方案。您最好的选择是在基于 *nix 的系统上使用 pollselect,在 Windows 上使用 WaitForSingleObjectWaitForMultipleObjects

您可以通过创建一个代理 streambuffer 类来透明地完成此操作,该类将调用转发给真正的 streambuffer 对象。这将允许您在进行实际读取之前调用适当的 wait 函数。它可能看起来像这样......

class MyStreamBuffer : public std::basic_streambuf<char>
{
public:
MyStreamBuffer(std::fstream& streamBuffer, int timeoutValue)
: timeoutValue_(timeoutvalue),
streamBuffer_(streamBuffer)
{
}

protected:
virtual std::streamsize xsgetn( char_type* s, std::streamsize count )
{
if(!wait(timeoutValue_))
{
return 0;
}

return streamBuffer_.xsgetn(s, count);
}

private:
bool wait() const
{
// Not entirely complete but you get the idea
return (WAIT_OBJECT_0 == WaitForSingleObject(...));
}

const int timeoutValue_;
std::fstream& streamBuffer_;
};

您需要在每次通话时都这样做。它可能会有点乏味,但会提供一个透明的解决方案来提供超时,即使在客户端代码中可能未明确支持超时也是如此。

关于c++ - 如何在 C++ 中读取最多 X 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16113989/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com