当前位置: 技术问答>linux和unix
pthread_cond_wait 没起作用?
来源: 互联网 发布时间:2016-12-27
本文导语: #include #include #include class CMythread { public: CMythread() { Init(); } int Init() { m_bExit = false; int ret = 0; ret = pthread_cond_init(&m_tCond, NULL); ret = pthread_cond_init(&m_tCond, NULL); return ret; } ~CMythread() { } void SetCmd() {...
#include
#include
#include
class CMythread
{
public:
CMythread()
{
Init();
}
int Init()
{
m_bExit = false;
int ret = 0;
ret = pthread_cond_init(&m_tCond, NULL);
ret = pthread_cond_init(&m_tCond, NULL);
return ret;
}
~CMythread()
{
}
void SetCmd()
{
pthread_cond_signal(&m_tCond);
printf("发送信号n");
}
void Excute()
{
int ret = 0;
while(!m_bExit)
{
printf("进入 pthread_cond_wait 等待n");
ret = pthread_cond_wait(&m_tCond, &m_mutex);
if( EINVAL == ret )
{
printf("== EINVALn");
}
printf("等待结束 excute a cmdn");
}
}
void SetExit(bool exit)
{
m_bExit = exit;
}
static void * Run( void *arg )
{
CMythread *pthread = (CMythread*)arg;
pthread->Excute();
return NULL;
}
pthread_t CreateThread()
{
int ret = pthread_create(&m_handle, NULL, Run, this);
printf("create return %dn", ret);
usleep(10000);//10毫秒
return m_handle;
}
protected:
pthread_t m_handle;
pthread_cond_t m_tCond;
pthread_condattr_t m_tCondAttr;
pthread_mutex_t m_mutex;
bool m_bExit;
};
CMythread th1;
th1.CreateThread();
th1.SetCmd();
|
条件变量的使用需要加锁的,只要你想用cond_wait,不管你的互斥量有没有用,都要锁住.
你这里情况 while(!m_bExit) 中的m_bExit就是一个共享变量,理应加锁,就算你访问它时候不想加锁,那也起码要让m_bExit加上volatile声明,并且把你的wait用锁包起来。
就变成下面这个样子了:
volatile bool m_bExit;
void Excute()
{
int ret = 0;
while(!m_bExit)
{
printf("进入 pthread_cond_wait 等待n");
pthread_mutex_lock(&m_mutex);
ret = pthread_cond_wait(&m_tCond, &m_mutex);
pthread_mutex_unlock(&m_mutex);
if( EINVAL == ret )
{
printf("== EINVALn");
}
printf("等待结束 excute a cmdn");
}
}
你这里情况 while(!m_bExit) 中的m_bExit就是一个共享变量,理应加锁,就算你访问它时候不想加锁,那也起码要让m_bExit加上volatile声明,并且把你的wait用锁包起来。
就变成下面这个样子了:
volatile bool m_bExit;
void Excute()
{
int ret = 0;
while(!m_bExit)
{
printf("进入 pthread_cond_wait 等待n");
pthread_mutex_lock(&m_mutex);
ret = pthread_cond_wait(&m_tCond, &m_mutex);
pthread_mutex_unlock(&m_mutex);
if( EINVAL == ret )
{
printf("== EINVALn");
}
printf("等待结束 excute a cmdn");
}
}
|
volatile bool m_bExit;
void Excute()
{
int ret = 0;
pthread_mutex_lock(&m_mutex);
while(!m_bExit)
{
printf("进入 pthread_cond_wait 等待n");
ret = pthread_cond_wait(&m_tCond, &m_mutex);
if( EINVAL == ret )
{
printf("== EINVALn");
}
printf("等待结束 excute a cmdn");
}
pthread_mutex_unlock(&m_mutex);
}
好像应该把锁锁在while外面吧
|
pthread_cond_wait前后要加锁。