pthread_mutex_t封装

//Mutex.cpp
#include
< pthread.h >
#include
< iostream >
using namespace 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);

return 0 ;

你可能感兴趣的:(pthread_mutex_t封装)