Data protection and sharing data between threads
Even though multithreading makes processes run asynchronously, there will be times when threads must stop and wait for other threads. This usually happens when both threads modify the same variable simultaneously. It is common to force threads to wait for one another to protect shared resources, such as data. Qt 6 also provides both low-level methods and high-level mechanisms to synchronize threads.
How to do it…
We will continue to use the code from the previous example project, since we have already established a working program with multithreading:
- Open up
myworker.h
and add the following header:#include <QObject> #include <QDebug> #include <QMutex>
- Then, we will add two new variables and make some changes to the class constructor:
public: explicit MyWorker(QMutex *mutex); int* myInputNumber; QMutex* myMutex; signals: ...