http://blog.csdn.net/chexlong/article/details/7058283
在上篇用C++實現了Win32平臺上的多線程互斥鎖,這次寫個Linux平臺上的,同樣參考了開源項目C++ Sockets的代碼,在此對這些給開源項目做出貢獻的鬥士們表示感謝!
下邊分別是互斥鎖類和測試代碼,已經在Fedora 13虛擬機上測試通過。
Lock.h
- #ifndef _Lock_H
- #define _Lock_H
- #include <pthread.h>
- //鎖接口類
- class ILock
- {
- public:
- virtual ~ILock() {}
- virtual void Lock() const = 0;
- virtual void Unlock() const = 0;
- };
- //互斥鎖類
- class CMutex : public ILock
- {
- public:
- CMutex();
- ~CMutex();
- virtual void Lock() const;
- virtual void Unlock() const;
- private:
- mutable pthread_mutex_t m_mutex;
- };
- //鎖
- class CMyLock
- {
- public:
- CMyLock(const ILock&);
- ~CMyLock();
- private:
- const ILock& m_lock;
- };
- #endif
Lock.cpp
- #include "Lock.h"
- //動態方式初始化互斥鎖
- CMutex::CMutex()
- {
- pthread_mutex_init(&m_mutex, NULL);
- }
- //註銷互斥鎖
- CMutex::~CMutex()
- {
- pthread_mutex_destroy(&m_mutex);
- }
- //確保擁有互斥鎖的線程對被保護資源的獨自訪問
- void CMutex::Lock() const
- {
- pthread_mutex_lock(&m_mutex);
- }
- //釋放當前線程擁有的鎖,以使其它線程可以擁有互斥鎖,對被保護資源進行訪問
- void CMutex::Unlock() const
- {
- pthread_mutex_unlock(&m_mutex);
- }
- //利用C++特性,進行自動加鎖
- CMyLock::CMyLock(const ILock& m) : m_lock(m)
- {
- m_lock.Lock();
- }
- //利用C++特性,進行自動解鎖
- CMyLock::~CMyLock()
- {
- m_lock.Unlock();
- }
測試代碼
- // pthread_mutex.cpp : 定義控制檯應用程序的入口點。
- //
- #include <iostream>
- #include <unistd.h>
- #include "Lock.h"
- using namespace std;
- //創建一個互斥鎖
- CMutex g_Lock;
- //線程函數
- void * StartThread(void *pParam)
- {
- char *pMsg = (char *)pParam;
- if (!pMsg)
- {
- return (void *)1;
- }
- //對被保護資源(以下打印語句)自動加鎖
- //線程函數結束前,自動解鎖
- CMyLock lock(g_Lock);
- for( int i = 0; i < 5; i++ )
- {
- cout << pMsg << endl;
- sleep( 1 );
- }
- return (void *)0;
- }
- int main(int argc, char* argv[])
- {
- pthread_t thread1,thread2;
- pthread_attr_t attr1,attr2;
- char *pMsg1 = "First print thread.";
- char *pMsg2 = "Second print thread.";
- //創建兩個工作線程,分別打印不同的消息
- pthread_attr_init(&attr1);
- pthread_attr_setdetachstate(&attr1,PTHREAD_CREATE_JOINABLE);
- if (pthread_create(&thread1,&attr1, StartThread,pMsg1) == -1)
- {
- cout<<"Thread 1: create failed"<<endl;
- }
- pthread_attr_init(&attr2);
- pthread_attr_setdetachstate(&attr2,PTHREAD_CREATE_JOINABLE);
- if (pthread_create(&thread2,&attr2, StartThread,pMsg2) == -1)
- {
- cout<<"Thread 2: create failed"<<endl;
- }
- //等待線程結束
- void *result;
- pthread_join(thread1,&result);
- pthread_join(thread2,&result);
- //關閉線程,釋放資源
- pthread_attr_destroy(&attr1);
- pthread_attr_destroy(&attr2);
- int iWait;
- cin>>iWait;
- return 0;
- }
編譯成功後,運行程序
同樣,若將下邊代碼註釋掉,重新編譯
- //CMyLock lock(g_Lock);
運行程序
結果顯而易見。