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はい、私の悪い –