I’m currently writing some code to handle serial communications between an embedded system and a computer. The embedded system can be disconnected and reconnected freely and my code needs to be able to handle this graciously.
My approach is to handle the serial communicatiouns asynchroulously in a seperate thread. When the serial device disconnects the thread exits and I can attempt to reconnect. This should start a new thread and resume the communications.
#include <thread>
void SerialCommunication(std::stop_token stoken)
{
ControllerSerial.Connect();
while (true)
{
// Read the string
if (bytes > 0) {
// If there are bytes, parse them
}
else {
// If there are no bytes then the connection is lost, exit the thread
break;
}
if (stoken.stop_requested()) {
// Exit the thread when requested to
break;
}
}
}
// empty jthread as a placeholder
std::jthread SerialCommThread;
int main(int, char**)
{
if (ImGui::Button("Start comms"))
{
SerialCommThread = std::jthread(&SerialCommunication);
}
if (ImGui::Button("Stop comms"))
{
SerialCommThread.request_stop();
SerialCommThread.join();
}
}
When I run the code and click the Start comms
button the thread runs and my data is parsed correctly. When I click Stop comms
the SerialCommThread
is exited and the data stops coming in.
However, if I now click Start comms
again, the SerialCommThread
exits immediately.
I’m assuming that I’m making a completely new thread that can be accessed via SerialCommThread
. But it seems there is some persistance somewhere and I haven’t been able to figure out where this comes from.