原作者:chexlong 原文地址: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);
- }
-
- CMyLock::CMyLock(const ILock& m) : m_lock(m)
- {
- m_lock.Lock();
- }
-
- CMyLock::~CMyLock()
- {
- m_lock.Unlock();
- }
测试代码
-
- #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;
- }
编译成功后,运行程序

同样,若将下边代码注释掉,重新编译
运行程序

结果显而易见。
【转】Linux平台上用C++实现多线程互斥锁
原文:http://www.cnblogs.com/gkwang/p/4482935.html