views:

46

answers:

2

I have a C++/Qt QThread worker thread, which stores its current status as an ENUM (e.g. values such as Working, Finished). Only the worker thread sets the ENUM.

I need to be able to read the status of the worker thread from another thread (the GUI thread), to display on the screen whether work is being done.

Is it safe to read/write the ENUM in one thread (worker), and read in other threads? Otherwise, should I use locking like QMutex in places where it is read/written?

A: 

As Neil said: Yes, you need locking. For your use case QReadWriteLock should be better suited than QMutex.

Frank
A: 

A more Qt-specific way to do this would be to have the worker thread emit a signal with its state whenever the state changes. Then the GUI would connect to the signal and update whatever it needs to for the state of the worker thread. If you do this, and pass the state by value, you shouldn't need any mutex protection of the state (since the value is copied when you emit the signal, that copy is never changed, and the copy is read in the UI thread). If you still need to query the thread for its state at different times, however, you'll still need locking.

Caleb Huitt - cjhuitt