我有一个使用 Asio 与远程系统对话的项目。我已将所有 Asio 代码封装在一个类中,该类在构造函数中打开一个同步连接,然后提供一个公共(public)方法,以便该类的用户可以通过套接字进行写入。这些方法执行同步 asio::write
,然后调用 asio::async_read
。
现在我的问题:
远程系统的响应时间未知,所以我需要让用户知道它必须等待。我正在考虑使用状态机执行此操作,该状态机在用户执行 asio::write
时初始化,并在 asio::async_read
的回调中再次更新。这意味着客户端代码在等待读取回调时必须在不确定的时间内循环标志,这对我来说似乎很脆弱。
是否有更好的机制来通知调用代码状态已更改?如果客户端代码正在循环,是否会调用 asio::async_read
的回调并更新标志?
最佳答案
按如下方式使用 boost::condition_variable:
//globals
boost::mutex mut;
boost::condition_variable cond;
bool waitflag = false;
bool response_available = false;
// inside async_read callback
bool waited;
{
boost::mutex::scoped_lock lock(mut);
if ((waited = waitflag)) // check if client loop is waiting for us
waitflag = false;
response_available = true;// write also any additional data to be read by client here
}
if (waited)
cond.notify_one(); // notify client
// inside client loop, use a short waiting time if the loop needs to perform other tasks simultaneously
{
boost::mutex::scoped_lock lock(mut);
if (!response_available) {
waitflag = true; // signal that we are waiting for callback
cond.timed_wait(lock, boost::posix_time::milliseconds(100));
}
if (response_available) { // check if data arrived
}
}
关于c++ - 与 asio::async_read 一起使用的正确模式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40110285/