线程的互斥和同步(4)- Qt中的互斥锁(QMutex和QMutexLocker)

上一篇文章主要介绍了Windows的互斥锁
线程的互斥和同步(3)- Windows的互斥锁

Linux也有自己API来操作互斥锁,对于跨平台的操作,Qt帮助我们使用一套代码实现相同的效果。
Qt中使用类 QMutexQMutexLocker 来实现和管理互斥锁。


  1. QMutex 的主要函数有:
  • lock (); 加锁,如果该互斥锁被占用,该函数阻塞,直到互斥锁被释放。
  • unlock (); 解锁
  • bool tryLock (int timeout = 0);
    表示尝试去加锁,timeout 为超时时间。如果互斥锁为可用状态,该函数会占用该互斥锁,并返回 true ,否则返回 false 。如果互斥锁被另一个线程占用,该函数会等待 timeout 毫秒直到互斥锁为可用状态。
  1. QMutexLocker 类的主要作用是用来管理 QMutex
    使用 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


作者:douzhq
个人主页:不会飞的纸飞机
文章同步页(可下载完整代码):线程的互斥和同步(3)- Qt中的互斥锁(QMutex和QMutexLocker)

发布了101 篇原创文章 · 获赞 95 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/douzhq/article/details/104365178
今日推荐