I'm using Boost Asio for reading my USB data. It works great! But I have some conserns.
I'm using synchronous reading (blocking read) when I want to read an incoming message. The reason why I'm choosing blocking read is because I want to read the message directly when it arrives. I have a feeling that if I'm using asynchronous (Non blocking read) read, then I might loose the first data of the incoming data.
My code for reading data is
// Atomic variable for the thread
std::atomic<bool> dataReceived(false);
// Start a read thread
std::thread readThread([&]() {
constexpr std::size_t buffer_size = 1024;
std::array<char, buffer_size> buffer;
boost::system::error_code error;
std::size_t bytes_transferred = 0;
try {
bytes_transferred = deviceUSB.read_some(boost::asio::buffer(buffer), error);
}
catch (...) {}
if (!error) {
dataRX.assign(buffer.begin(), buffer.begin() + bytes_transferred);
dataReceived = true;
}
});
// Write data
deviceUSB.write_some(boost::asio::buffer(dataTX, size));
// Check if data has been received or timeout has occurred
bool timeout = false;
auto startTime = std::chrono::steady_clock::now();
auto timeoutDuration = std::chrono::milliseconds(timeOutMilliseconds);
while (!dataReceived && !timeout) {
auto currentTime = std::chrono::steady_clock::now();
auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - startTime);
// Check if timeout has occurred
if (elapsedTime >= timeoutDuration) {
timeout = true;
readThread.detach(); // Kill the thread
}
}
// End the thread
if (readThread.joinable()) {
readThread.join();
}
And the problem is this line. I don't actually kill the thread, just detaching it.
readThread.detach(); // Kill the thread
If I detach it, then the thread will still live on. My suggestion is to use a while-loop instead of a thread, together with asynchronous read. If the message does not arrive within a certain limit, then the while loop will end.
Question:
Is asynchronous + while loop
bool run = true;
while(run){
bytes_transferred = deviceUSB.async_read_some(boost::asio::buffer(buffer), error);
if(bytes_transferred > 0){
run = false;
}
}
the same as synchronous inside Boost Asio?
bytes_transferred = deviceUSB.read_some(boost::asio::buffer(buffer), error);