Max Beikirch
Max Beikirch

Reputation: 2143

Qt Threading synchronization

Consider the the following situation:

I have a QThread that constantly modifies a variable (let's call it counter) and a QTimer that periodically reads counter. I know that I have to synchronize variables that might be modified by multiple threads at the same time but - do I need synchronization in this case as well, when there is only one thread reading and one thread writing a variable?

Upvotes: 2

Views: 758

Answers (3)

Phlucious
Phlucious

Reputation: 3843

Protect your counter variable with a QReadWriteLock. When you're editing the counter variable in your thread(s), have them lock it with a QWriteLocker, which will lock out any other attempts to write OR read. When your main thread checks the value of counter, lock it with a QReadLocker, which will only lock if a write lock is current active.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477040

Yes, you always need synchronisation — if for no other reason than that the standard says that your program has undefined behaviour if there is a data race.

You can either synchronize with a mutex that guards the counter variable, which I suppose is the "traditional" way, or you can use an std::atomic<int> variable for your counter, which you can access without creating a data race.

Upvotes: 2

dtech
dtech

Reputation: 49289

The scenario you describe isn't safe, you will still need synchronization. There are several classes in Qt that can help you with that, via a locking or a lock-free mechanism.

Take a peek at QMutex, QReadWriteLock, QSemaphore, QWaitCondition, QFuture, QFutureWatcher, QAtomicInt and QAtomicPointer. Plus you have std::atomic<T> in C++11.

Upvotes: 4

Related Questions