pthread_mutex_t封装

本文介绍了一种封装pthread_mutex线程同步的方法,通过自定义ThreadMutex类简化了线程同步的操作过程。该方法实现了线程锁的初始化、锁定、解锁及销毁功能,并提供了测试示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常常需要使用pthread_mutex线程同步,每次都要使用pthread_mutex_init, pthread_mutex_lock, pthread_unlock, pthread_mutex_destroy这几个函数,干脆封装一下,以便以后重用。

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->//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;                                             
}    
转载自:http://www.cppblog.com/bujiwu/archive/2009/11/08/pthread_mutex.html