Linux平臺上用C++實現多執行緒互斥鎖
阿新 • • 發佈:2019-01-01
在上篇用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);
執行程式
結果顯而易見。