Production consumer issues
-There are n producers who make products at the same time and store them in the warehouse
-There are m consumers who need to take products out of the warehouse at the same time
-Rules:
·When the warehouse is not full, any producer can store the products
·When the warehouse is not empty, any consumer can take out the product
#include <QCoreApplication> #include <QThread> #include <QDebug> static QString g_store; class Producer : public QThread { protected: void run() { int count = 0; while(true) { g_store.append(QString::number((count++) % 10)); qDebug() << objectName() << " : " + g_store; msleep(1); } } }; class Customer : public QThread { protected: void run() { while(true){ if(g_store != "") { g_store.remove(0,1); qDebug() << objectName() << " : " + g_store; } msleep(1); } } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Producer p; Customer c; p.setObjectName("p"); c.setObjectName("c"); p.start(); c.start(); return a.exec(); }
Critical Resource
-Only one thread is allowed to access (read / write) resources at a time
Mutual exclusion (competition) between threads
-Multiple threads need to access critical resources at the same time
QMutex class is a thread lock to ensure mutual exclusion between threads
-Using thread lock can ensure the security of critical resources
Key member functions in QMutex
-void lock()
·When the lock is idle, acquire the lock and continue to execute
·When the lock is acquired, block and wait for the lock to release
-void unlock()
·Release lock (acquisition and release of the same lock must be paired in the same thread)
QMutex usage example
QMutex mutex;//Using shi mutex.lock(); // do something with critical resource mutex.unlock(); ps:If mutex In the call unlock()When it is idle, the behavior of the program is undefined!
#include <QCoreApplication> #include <QThread> #include <QMutex> #include <QDebug> static QMutex g_mutex; static QString g_store; class Producer : public QThread { protected: void run() { int count = 0; while(true) { g_mutex.lock(); g_store.append(QString::number((count++) % 10)); qDebug() << objectName() << " : " + g_store; g_mutex.unlock(); msleep(1); } } }; class Customer : public QThread { protected: void run() { while(true){ g_mutex.lock(); if(g_store != "") { g_store.remove(0,1); qDebug() << objectName() << " : " + g_store; } g_mutex.unlock(); msleep(1); } } }; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Producer p; Customer c; p.setObjectName("p"); c.setObjectName("c"); p.start(); c.start(); return a.exec(); }
Conclusion:
-Critical resources can only be accessed (read / write) by one thread at a time
-QMutex is used to protect critical resources
-Threads can only access critical resources after acquiring locks
-When the lock is acquired by another thread, the current thread enters the waiting state
-Acquisition and release of thread locks must occur in pairs in the same thread