Linux c++互斥锁

#ifndef _Lock_H
#define _Lock_H


#include <pthread.h>
#include <iostream>
using namespace std;
//锁接口类
class ILock
{
public:
virtual ~ILock() {}


virtual void Lock() 
{
cout<<"ILock"<<endl;
}
virtual void Unlock()
{
cout<<"ILock Unlock"<<endl;
}
};


//互斥锁类
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:
ILock m_lock;
};




#endif


#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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值