常常需要使用pthread_mutex线程同步,每次都要使用pthread_mutex_init, pthread_mutex_lock, pthread_unlock, pthread_mutex_destroy这几个函数,干脆封装一下,以便以后重用。
//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;
}
通过g++ -o Mutex Mutex.cpp -lpthread编译。