Search code examples
c++functioncallexitinfinite

C++ exit function from another function


I have created a class for the serial link with a read function. I use boost::asio::read for reading data from the serial link. But the read function waits infinite until a byte has been received.

I want to create a thread that stops the read function if the maximum wait time has passed (because there seems a malfunction in the system).

Is it possible to exit a function in C++ from another function? Or cancel the read function call from the other function?

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 
}

Solution

  • How about you do your reading in a thread (pthread_t thread_read;), then launch the timer in another thread (pthread_t thread_timer;).

    After the desired periob, you cancel the reading thread (pthread_cancel(thread_read);)