線程的互斥和同步(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)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章