上一篇文章主要介绍了Windows的互斥锁
线程的互斥和同步(3)- Windows的互斥锁
Linux也有自己API来操作互斥锁,对于跨平台的操作,Qt帮助我们使用一套代码实现相同的效果。
Qt中使用类 QMutex 和 QMutexLocker 来实现和管理互斥锁。
使用 QMutexLocker 的好处是,可以防止线程死锁。
该对象在构造的时候加锁,析构的时候解锁。
下面是一个关于互斥锁的使用例子,
同样使用了 CThread,头文件:
#include <QMutex>
class QtMutexThread : public CThread
{
public:
void run(void) override;
private:
static QMutex m_mutex;
};
源文件:
QMutex QtMutexThread::m_mutex;
int number = 0;
void QtMutexThread::run(void)
{
while (1)
{
{
QMutexLocker locker(&m_mutex);
std::cout << "Current Thread: " << ::GetCurrentThreadId() \
<< ", Value: " << number++ << std::endl;
}
Sleep(1000);
}
}
调用部分:
int main(int argc, char *argv[])
{
QtMutexThread thread1;
QtMutexThread thread2;
QtMutexThread thread3;
thread1.start();
thread2.start();
thread3.start();
thread1.wait();
thread2.wait();
thread3.wait();
}
输出结果:
Current Thread: 14668, Value: 0
Current Thread: 1496, Value: 1
Current Thread: 16604, Value: 2
Current Thread: 14668, Value: 3
Current Thread: 1496, Value: 4
Current Thread: 16604, Value: 5
Current Thread: 14668, Value: 6
Current Thread: 1496, Value: 7
Current Thread: 16604, Value: 8
Current Thread: 14668, Value: 9
Current Thread: 1496, Value: 10
Current Thread: 16604, Value: 11
Current Thread: 14668, Value: 12
Current Thread: 1496, Value: 13