简体   繁体   English

C++ 中的线程串行端口通信与 Qt

[英]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.我正在编写一个 QT 桌面应用程序,它将显示从串行端口接收到的信息。 Therefore a class was created and packed into an DLL using standard Windows API features to communicate with the connected device (CreateFile, ReadFile, WriteFile, ...).因此,使用标准的 Windows API 功能创建了一个类并将其打包到 DLL 中,以便与连接的设备(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.目前,计时器以预定义的速率 [< 200 毫秒] 调用 DLL,这会导致 gui 冻结一小段时间。 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.目标是,gui 不会冻结。

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.编辑:我使用 QThread 派生的工作类和一个被遮蔽的 run() 函数解决了这个问题,它在后台处理串行端口通信并在新信息可用时更新 gui。

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.在许多用例中,在单独的线程上执行所有阻塞(同步)I/O 是一种很好的做法,尤其是在涉及图形用户界面时。 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). 这是我参考的关于同步 I/O 挑战的页面(而不是异步,其中您的代码不会阻塞但仍然是单线程的,或者您正在讨论的并行)。 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? GUI 会阻塞直到有数据吗? 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?如果 I/O 设备不再可用,程序会做什么? For example, if it is a USB-to-serial adapter, what happens if the adapter is unplugged?例如,如果是USB转串口适配器,拔掉适配器会怎样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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