pthread_mutex_t封装

来源:互联网 发布:奥格斯堡同盟 知乎 编辑:程序博客网 时间:2024/06/06 00:51
//Mutex.cpp
#include
<pthread.h>
#include
<iostream>
usingnamespace std;

class ThreadMutex
{
public:
ThreadMutex()
{
pthread_mutex_init(
&mtx, NULL);
}

~ThreadMutex()
{
pthread_mutex_destroy(
&mtx );
}

inline
void Lock()
{
pthread_mutex_lock(
&mtx );
}

inline
void UnLock()
{
pthread_mutex_unlock(
&mtx );
}

private:
pthread_mutex_t mtx;
};

//以下为测试用例
ThreadMutex g_Mutex;

void*PrintMsg(void*lpPara)
{
char*msg = (char*)lpPara;

g_Mutex.Lock();

for(int i=0; i< 5; i++ )
{
cout
<< msg<< endl;
sleep(
1 );
}

g_Mutex.UnLock();

return NULL;
}

int main()
{
pthread_t t1,t2;

//创建两个工作线程,第1个线程打印10个1,第2个线程打印10个2。
pthread_create( &t1, NULL,&PrintMsg, (void*)"First print thread" );
pthread_create(
&t2, NULL,&PrintMsg, (void*)"Second print thread" );

//等待线程结束
pthread_join( t1, NULL);
pthread_join( t2, NULL);

return0;