简体   繁体   中英

How to run Qt UI and Linux message queue reception thread in parellel?

I am developing an UI using QTCreator using CPP. My requirement is to run a UI and need to continuously poll linux Message queue using function msgrcv() whether any data is coming to the queue. I created one thread to continuously monitor the reception queue message. While starting and running the mentioned thread, UI got stuck. Any solution for running the thread and UI in parallel?

It's impossible to tell without seeing your code. However, if the poll operation is non-blocking, then you don't actually need a thread. You can instead register a piece of code that Qt's event loop will run on each UI event loop iteration. You do that using a 0ms QTimer:

void poll_function();

// ...

QTimer poll_timer;
QObject::connect(&poll_timer, &QTimer::timeout, poll_function);
poll_timer.start();

Of course, in the above example code, poll_function() will stop getting called once poll_timer goes out of scope. In your real code, you should use a QTimer that stays alive for as long as you need it. Should probably be a data member of your QApplication subclass.

If poll_function() blocks though, then this approach will not work as it will block the UI. So you should make sure to tell msgrcv() to not block. From the man page :

If no message of the requested type is available and IPC_NOWAIT isn't specified in msgflg, the calling process is blocked

So make sure you include IPC_NOWAIT in the msgflg flags when calling msgrcv() .

If polling on every UI event loop iteration is too much overhead, then you can instead set a normal timeout interval in milliseconds:

poll_timer.setInterval(500);

This will call your poll function every 500ms.

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