简体   繁体   中英

threaded serial port communication in C++ with Qt

I am writing an QT desktop application that is going to display information received from a serial port. Therefore a class was created and packed into an DLL using standard Windows API features to communicate with the connected device (CreateFile, ReadFile, WriteFile, ...).

At the moment a timer calls the DLL at a predefined rate [< 200ms] and this leads the gui to freeze for short periods. Because of that i am thinking of using a thread to do the serial port stuff, that is also going to display everything.

Is is better to use threads for this problem or should i rewrite the class to do the work event based? The target is, that the gui doesnt freeze.

Edit: I solved the problem using a QThread derived worker class with an overshadowed run() function, that handles the serial port communication in the background and updates the gui as new informations are available.

It is good practice in many use cases to do all blocking (synchronous) I/O on a separate thread, especially when a graphical user interface is involved. Here's a page I've referenced regarding the challenges with synchronous I/O (as opposed to asynchronous where your code doesn't block but is still single-threaded, or parallel as you're discussing). There are more issues than just what you brought up, for example:

  • What if there is no data available? Does the GUI block until there is data? For example, if the sender was off then there would be no data
  • What does the program do if the I/O device is no longer available? For example, if it is a USB-to-serial adapter, what happens if the adapter is unplugged?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM