On 10/22/2012 10:57 AM, Bo Thorsen
wrote:
Den 22-10-2012 03:38, Syam Krishnan
skrev:
A question to all:
I have a GUI application. I need to do some task (for example,
periodically reading/writing from a serial port) in the
background that has nothing to do with GUI. i.e. the background
task does not touch GUI or need to emit signals or have slots.
It just needs to be there, reading & writing to shared
memory (protected by Mutex).
Now, the way I've been doing this is by creating a new class
from QThread and overriding run() to implement my thread
function. The function is often a loop that runs till a public
volatile bool variable is set, indicating time to quit. For
doing periodic stuff, it sleeps for few milliseconds (by using
nanosleep()). When the program is terminated, in main windows'
close event, or some other suitable place, I set the thread loop
control variable and wait for the thread to terminate
(QThread::wait()).
Is there any other recommended or better way to do it? Note that
I don't need to do any Qt stuff (update GUI, signals & slots
etc.) in my 'worker' thread.
There's nothing wrong with the way you use QThread. It's one of
the examples of when it's perfectly fine to use it by subclassing.
However, when somebody mentions volatile bools and shared memory,
I get ticks and start hearing 1980's music. If you want to improve
something, getting rid of this stuff is a much better candidate.
Get rid of this? But replace it with what? As you mentioned in
another reply, the volatile bool is used as a loop control variable.
The worst that can happen is one additional iteration of the loop,
which in my case is absolutely of no impact.
My data from serial port / network socket is asynchronous, but can
be expected more or less periodically in the ideal case. My
experience with timers for reading from ordinary serial ports
(better with PCI boards) isn't very good. With a select() call in a
thread, everything's great and there's no data miss.
Syam
|
_______________________________________________
Interest mailing list
Interest@qt-project.org
http://lists.qt-project.org/mailman/listinfo/interest