当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - 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?

网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: