QMutex
同一个QMutex lock() 时,其他的 lock() 操作要等待 locked 的地方 unlock() (可以保证顺序执行)
测试代码:
#include <iostream>
#include <QThread>
#include <QMutex>
using namespace std;
class myThread1 : public QThread {
public:
myThread1(int &num, QMutex& mutex) : _num(num), _mutex(mutex) {}
~myThread1() {}
void run() {
_mutex.lock();
cout << "ThreadId: " << QThread::currentThread() << endl;
cout << "thread1 num before: " << _num << endl;
_num *= 5;
cout << "thread1 num: " << _num << endl;
_num /= 4;
cout << "thread1 num: " << _num << endl;
_mutex.unlock();
}
private:
int &_num;
QMutex &_mutex;
};
class myThread2 : public QThread {
public:
myThread2(int &num, QMutex& mutex) : _num(num), _mutex(mutex) {}
~myThread2() {}
void run() {
_mutex.lock();
cout << "ThreadId: " << QThread::currentThread() << endl;
cout << "thread2 num before: " << _num << endl;
_num *= 3;
cout << "thread2 num: " << _num << endl;
_num /= 2;
cout << "thread2 num: " << _num << endl;
_mutex.unlock();
}
private:
int &_num;
QMutex &_mutex;
};
int main()
{
int num = 6;
QMutex mutex1;
QMutex mutex2;
myThread1 t1(num, mutex1);
myThread2 t2(num, mutex2);
t1.start();
t2.start();
t1.wait();
t2.wait();
cout << "num: " << num << endl;
}
多运行几次,可以发现,输出的结果不相同。
原来的理解:QMutex 可以保护 lock() 和 unlock() 之间的变量(例子中为 _num),在执行到unlock() 之前,别的线程都不可以修改_num 的值。这种理解是错的
QMutex 能限制的从来都只有自身,如果一个QMutex 对象已经进行的 lock() 操作,但是没有 unlock(), 其它地方的 lock() 操作都会阻塞等待,直到 unlock() 执行。QMutex 就是通过这种方式保证同时只有一个线程在操作共有变量的。
上面的例子中传了两个不同的 QMutex 进去,所有并没有起到锁的作用,各自还是可以访问
标签:include,Qt,lock,unlock,num,QMutex,mutex,多线程 From: https://www.cnblogs.com/AngleLin/p/17329509.html