Replace semaphore with pthread_cond_t in job queue

This commit is contained in:
Nathan Fisher 2023-07-31 11:24:03 -04:00
parent b0fa9d1953
commit a77a2c30b1
2 changed files with 9 additions and 6 deletions

View file

@ -34,8 +34,9 @@
#define JOBQ_H
#include <pthread.h>
#include <semaphore.h>
#include <stddef.h>
#include <stdlib.h>
#include <sys/_pthreadtypes.h>
#include "haggis.h"
@ -53,7 +54,8 @@ struct _job_node {
typedef struct _job_node haggis_jobq_node;
typedef struct {
sem_t *sem;
pthread_cond_t *cond;
size_t count;
pthread_mutex_t *mutex;
haggis_jobq_node *head;
haggis_jobq_node *tail;

View file

@ -47,16 +47,19 @@ int haggis_jobq_push(haggis_jobq *queue, haggis_job *job) {
queue->tail->prev = new;
queue->tail = new;
}
queue->count++;
pthread_mutex_unlock(queue->mutex);
return sem_post(queue->sem);
return 0;
}
haggis_job* haggis_jobq_pop(haggis_jobq *queue) {
haggis_jobq_node *j;
haggis_job *job;
sem_wait(queue->sem);
while (queue->count == 0)
pthread_cond_wait(queue->cond, queue->mutex);
pthread_mutex_lock(queue->mutex);
queue->count--;
j = queue->head;
job = j->job;
if (queue->tail == queue->head) {
@ -66,7 +69,5 @@ haggis_job* haggis_jobq_pop(haggis_jobq *queue) {
}
free(j);
pthread_mutex_unlock(queue->mutex);
if (sem_post(queue->sem) != 0)
return NULL;
return job;
}