Jiwu Bu

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  32 随笔 :: 0 文章 :: 25 评论 :: 0 Trackbacks
常常需要使用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编译。
posted on 2009-11-08 20:57 bujiwu 阅读(3926) 评论(0)  编辑 收藏 引用 所属分类: Linux

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理