Linux学习之互斥量的封装一:封装创建(pthread_mutex_init)和销毁(pthread_mutex_destroy)

本节的源程序基于"Linux学习之线程封装四:基于接口的封装"一节。

增加了封装的互斥量类"CLMutex"(互斥量的创建封装进构造函数,销毁封装进析构函数,还结合CLLog类增加了错误处理)。

头文件:

View Code
#ifndef CLMutex_H
#define CLMutex_H

#include <pthread.h>
#include "CLStatus.h"

class CLMutex
{
public:
/*
构造函数和析构函数出错时,会抛出字符串类型异常
*/
CLMutex();
virtual ~CLMutex();

CLStatus Lock();
CLStatus Unlock();

private:
CLMutex(const CLMutex&);
CLMutex& operator=(const CLMutex&);

private:
pthread_mutex_t m_Mutex;
};

#endif

实现:

View Code
#include "CLMutex.h"
#include "CLLog.h"

CLMutex::CLMutex()
{
int r = pthread_mutex_init(&m_Mutex, 0);
if(r != 0)
{
CLLog::WriteLogMsg("In CLMutex::CLMutex(), pthread_mutex_init error", r);
throw "In CLMutex::CLMutex(), pthread_mutex_init error";
}
}

CLMutex::~CLMutex()
{
int r = pthread_mutex_destroy(&m_Mutex);
if(r != 0)
{
CLLog::WriteLogMsg("In CLMutex::~CLMutex(), pthread_mutex_destroy error", r);
throw "In CLMutex::~CLMutex(), pthread_mutex_destroy error";
}
}

CLStatus CLMutex::Lock()
{
int r = pthread_mutex_lock(&m_Mutex);
if(r != 0)
{
CLLog::WriteLogMsg("In CLMutex::Lock(), pthread_mutex_lock error", r);
return CLStatus(-1, 0);
}
else
{
return CLStatus(0, 0);
}
}

CLStatus CLMutex::Unlock()
{
int r = pthread_mutex_unlock(&m_Mutex);
if(r != 0)
{
CLLog::WriteLogMsg("In CLMutex::Unlock(), pthread_mutex_unlock error", r);
return CLStatus(-1, 0);
}
else
{
return CLStatus(0, 0);
}
}

调用:

View Code
#include <iostream>
#include "CLThread.h"
#include "CLExecutiveFunctionProvider.h"
#include "CLMutex.h"

using namespace std;

struct SPara
{
int Flag;
CLMutex mutex;
};

class CLMyFunction : public CLExecutiveFunctionProvider
{
public:
CLMyFunction()
{
}

virtual ~CLMyFunction()
{
}

virtual CLStatus RunExecutiveFunction(void *pContext)
{
SPara *p = (SPara*)pContext;

p->mutex.Lock();

p->Flag++;

p->mutex.Unlock();

return CLStatus(0, 0);
}
};

int main()
{
CLExecutiveFunctionProvider *myfunction = new CLMyFunction();
CLExecutive *pThread = new CLThread(myfunction);

SPara *p = new SPara;
p->Flag = 3;

pThread->Run((void *)p);

p->mutex.Lock();

p->Flag++;
cout << p->Flag << endl;

p->mutex.Unlock();

pThread->WaitForDeath();

delete p;

delete pThread;
delete myfunction;

return 0;
}

简化了一定的操作。

posted @ 2011-10-21 18:00  lq0729  阅读(4903)  评论(1编辑  收藏  举报