【发布时间】:2012-06-15 13:48:25
【问题描述】:
为了理解pthread条件变量的代码,我写了自己的版本。它看起来正确吗?我在一个程序中使用它,它的工作,但工作速度惊人的快。最初程序大约需要 2.5 秒,而使用我的条件变量版本只需要 0.8 秒,并且程序的输出也是正确的。但是,我不确定我的实现是否正确。
struct cond_node_t
{
sem_t s;
cond_node_t * next;
};
struct cond_t
{
cond_node_t * q; // Linked List
pthread_mutex_t qm; // Lock for the Linked List
};
int my_pthread_cond_init( cond_t * cond )
{
cond->q = NULL;
pthread_mutex_init( &(cond->qm), NULL );
}
int my_pthread_cond_wait( cond_t* cond, pthread_mutex_t* mutex )
{
cond_node_t * self;
pthread_mutex_lock(&(cond->qm));
self = (cond_node_t*)calloc( 1, sizeof(cond_node_t) );
self->next = cond->q;
cond->q = self;
sem_init( &self->s, 0, 0 );
pthread_mutex_unlock(&(cond->qm));
pthread_mutex_unlock(mutex);
sem_wait( &self->s );
free( self ); // Free the node
pthread_mutex_lock(mutex);
}
int my_pthread_cond_signal( cond_t * cond )
{
pthread_mutex_lock(&(cond->qm));
if (cond->q != NULL)
{
sem_post(&(cond->q->s));
cond->q = cond->q->next;
}
pthread_mutex_unlock(&(cond->qm));
}
int my_pthread_cond_broadcast( cond_t * cond )
{
pthread_mutex_lock(&(cond->qm));
while ( cond->q != NULL)
{
sem_post( &(cond->q->s) );
cond->q = cond->q->next;
}
pthread_mutex_unlock(&(cond->qm));
}
【问题讨论】:
-
您正在释放
self节点而不将其从列表中删除。 -
@n.m.
self节点被signal和broadcast移除。 -
@JensGustedt 是的,我的错
-
我意识到这纯粹是教育性的,但我想我应该提到信号量不需要互斥锁来保证信号不会丢失。如果你
sem_post没有人在听,sem_wait仍然会在你下次打电话时接听它。信号量基本上是原子计数器,用于阻止以防止变为负数。 -
我认为
my_pthread_cond_signal和`my_pthread_cond_broadcast´ 有相同的实现,对吗?
标签: c linux multithreading gcc pthreads