首页 > 解决方案 > C++ 从另一个函数退出函数

问题描述

我为具有读取功能的串行链接创建了一个类。我使用 boost::asio::read 从串行链路读取数据。但是读取函数会无限等待,直到接收到一个字节。

如果最长等待时间已经过去,我想创建一个停止读取功能的线程(因为系统中似乎存在故障)。

是否可以从另一个函数中退出 C++ 中的函数?或者取消其他函数的读取函数调用?

std::string SerialLink::read(const int maxTime) {
  std::string data;
  std::vector < uint8_t > buf;
  const int readSize = 1;
  try {
    buf.resize(readSize);

    //boost::asio::read waits until a byte has been received
    boost::asio::read(port_, boost::asio::buffer(buf, readSize));
    data = buf.front();
  } 
catch (const std::exception & e) {
    std::cerr << "SerialLink ERROR: " << e.what() << "\n";
    return -1;
  }
  return data();
}

void threadTime() {
  //This function will keep track of the time and if maxTime has passed, the read function/function call must be cancelled and return -1 if possible 
}

标签: c++functioncallexitinfinite

解决方案


如果 port_是一个普通的文件描述符并且你有 POSIX 可用,你可能首先调用它selectpoll后者更容易使用),两者都提供了一个超时工具。

特定于设备和操作系统(您必须阅读文档),甚至可能允许ioctl获取可用数据量......


推荐阅读