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?
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.
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.
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.