pthread同步

关于pthread的同步,个人觉得没Windows做的好,在同步的时候,线程时间片分配不是很好,所以在Windows上,可以直接用CCriticalSection; 


这里简单说一下pthread同步:


pthread_mutex_t 变量;


示例:

pthread_mutex_t mutext_lock = PTHREAD_MUTEX_INITIALIZER;  //这是pthread种的宏定义初始化,当然也可以通过代码自定义初始化;


pthread_mutex_lock(&mutext_lock); 

//同步代码;

pthread_mutex_unlock(&mutext_lock); 



//结束:

pthread_mutex_destroy(&mutext_lock);


所以上述方法可以简单封装为一个类:


class XMutex
{
public:
XMutex();


~XMutex();


public:
void Lock();


BOOL TryLock();


void UnLock();


private:
XMutex(const XMutex&);
XMutex& operator=(const XMutex&);


private:


pthread_mutex_tm_mutex;


    pthread_mutexattr_t attr;


};



XMutex::XMutex()
{
int ret = -1;
//::pthread_mutexattr_t attr;
::pthread_mutexattr_init(&attr);
ret = ::pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP);
ASSERT(0 == ret);
ret = ::pthread_mutex_init( &m_mutex, &attr);
ASSERT(0 == ret);
// ret = ::pthread_mutexattr_destroy(&attr);
// ASSERT(0 == ret);
ret = 0;
}


XMutex::~XMutex()
{
int ret = ::pthread_mutexattr_destroy(&attr);
ASSERT(0 == ret);


ret = ::pthread_mutex_destroy(&m_mutex);
ASSERT(!ret && "the mutex is currently locked.");
ret = 0;
}


void XMutex::Lock()
{
int ret = ::pthread_mutex_lock(&m_mutex);
ASSERT(!ret && "the mutex is already locked by the calling thread.");
ret = 0;
}


BOOL XMutex::TryLock()
{
if (0 == ::pthread_mutex_trylock(&m_mutex))
{
return TRUE;
}
return FALSE;
}


void XMutex::UnLock()
{
int ret = ::pthread_mutex_unlock(&m_mutex);
ASSERT(!ret && "the  calling  thread  does  not  own  the mutex.");
ret = 0;
}

你可能感兴趣的:(pthread同步)