Replace semaphore with pthread_cond_t in job queue
This commit is contained in:
parent
b0fa9d1953
commit
a77a2c30b1
2 changed files with 9 additions and 6 deletions
|
@ -34,8 +34,9 @@
|
||||||
#define JOBQ_H
|
#define JOBQ_H
|
||||||
|
|
||||||
#include <pthread.h>
|
#include <pthread.h>
|
||||||
#include <semaphore.h>
|
#include <stddef.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include <sys/_pthreadtypes.h>
|
||||||
|
|
||||||
#include "haggis.h"
|
#include "haggis.h"
|
||||||
|
|
||||||
|
@ -53,7 +54,8 @@ struct _job_node {
|
||||||
typedef struct _job_node haggis_jobq_node;
|
typedef struct _job_node haggis_jobq_node;
|
||||||
|
|
||||||
typedef struct {
|
typedef struct {
|
||||||
sem_t *sem;
|
pthread_cond_t *cond;
|
||||||
|
size_t count;
|
||||||
pthread_mutex_t *mutex;
|
pthread_mutex_t *mutex;
|
||||||
haggis_jobq_node *head;
|
haggis_jobq_node *head;
|
||||||
haggis_jobq_node *tail;
|
haggis_jobq_node *tail;
|
||||||
|
|
|
@ -47,16 +47,19 @@ int haggis_jobq_push(haggis_jobq *queue, haggis_job *job) {
|
||||||
queue->tail->prev = new;
|
queue->tail->prev = new;
|
||||||
queue->tail = new;
|
queue->tail = new;
|
||||||
}
|
}
|
||||||
|
queue->count++;
|
||||||
pthread_mutex_unlock(queue->mutex);
|
pthread_mutex_unlock(queue->mutex);
|
||||||
return sem_post(queue->sem);
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
haggis_job* haggis_jobq_pop(haggis_jobq *queue) {
|
haggis_job* haggis_jobq_pop(haggis_jobq *queue) {
|
||||||
haggis_jobq_node *j;
|
haggis_jobq_node *j;
|
||||||
haggis_job *job;
|
haggis_job *job;
|
||||||
|
|
||||||
sem_wait(queue->sem);
|
while (queue->count == 0)
|
||||||
|
pthread_cond_wait(queue->cond, queue->mutex);
|
||||||
pthread_mutex_lock(queue->mutex);
|
pthread_mutex_lock(queue->mutex);
|
||||||
|
queue->count--;
|
||||||
j = queue->head;
|
j = queue->head;
|
||||||
job = j->job;
|
job = j->job;
|
||||||
if (queue->tail == queue->head) {
|
if (queue->tail == queue->head) {
|
||||||
|
@ -66,7 +69,5 @@ haggis_job* haggis_jobq_pop(haggis_jobq *queue) {
|
||||||
}
|
}
|
||||||
free(j);
|
free(j);
|
||||||
pthread_mutex_unlock(queue->mutex);
|
pthread_mutex_unlock(queue->mutex);
|
||||||
if (sem_post(queue->sem) != 0)
|
|
||||||
return NULL;
|
|
||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
|
|
Loading…
Add table
Reference in a new issue