seahag/jobq.c

75 lines
2.8 KiB
C
Raw Permalink Normal View History

2023-07-29 06:28:33 -04:00
/* _,.---._ .-._ .--.-. ,--.--------.
* _,..---._ ,-.' , - `. /==/ \ .-._/==/ //==/, - , -\
* /==/, - \ /==/_, , - \|==|, \/ /, |==\ -\\==\.-. - ,-./
* |==| _ _\==| .=. |==|- \| | \==\- \`--`\==\- \
* |==| .=. |==|_ : ;=: - |==| , | -| `--`-' \==\_ \
* |==|,| | -|==| , '=' |==| - _ | |==|- |
* |==| '=' /\==\ - ,_ /|==| /\ , | |==|, |
* |==|-, _`/ '.='. - .' /==/, | |- | /==/ -/
* `-.`.____.' `--`--'' `--`./ `--` `--`--`
* _ __ ,---. .-._ .=-.-. _,.----.
* .-`.' ,`..--.' \ /==/ \ .-._ /==/_ /.' .' - \
* /==/, - \==\-/\ \ |==|, \/ /, /==|, |/==/ , ,-'
* |==| _ .=. /==/-|_\ | |==|- \| ||==| ||==|- | .
* |==| , '=',\==\, - \ |==| , | -||==|- ||==|_ `-' \
* |==|- '..'/==/ - ,| |==| - _ ||==| ,||==| _ , |
* |==|, | /==/- /\ - \|==| /\ , ||==|- |\==\. /
* /==/ - | \==\ _.\=\.-'/==/, | |- |/==/. / `-.`.___.-'
* `--`---' `--` `--`./ `--``--`-`
*
* @(#)Copyright (c) 2023, Nathan D. Fisher.
*
* This is free software. It comes with NO WARRANTY.
* Permission to use, modify and distribute this source code
* is granted subject to the following conditions.
* 1/ that the above copyright notice and this notice
* are preserved in all copies and that due credit be given
* to the author.
* 2/ that any changes to this code are clearly commented
* as such so that the author does not get blamed for bugs
* other than his own.
*/
#include <stdlib.h> // free, malloc
2023-07-29 06:28:33 -04:00
#include "jobq.h"
2024-02-11 01:09:21 -05:00
int haggis_jobq_push(haggis_jobq *self, haggis_job *job) {
2023-07-29 06:28:33 -04:00
haggis_jobq_node *new = malloc(sizeof(haggis_jobq_node));
if (new == NULL)
return 1;
new->job = job;
2023-07-29 06:28:33 -04:00
new->next = new->prev = NULL;
2024-02-11 01:09:21 -05:00
pthread_mutex_lock(self->mutex);
if (self->tail == NULL) {
self->tail = self->head = new;
2023-07-29 06:28:33 -04:00
} else {
2024-02-11 01:09:21 -05:00
new->next = self->tail;
self->tail->prev = new;
self->tail = new;
2023-07-29 06:28:33 -04:00
}
2024-02-11 01:09:21 -05:00
self->count++;
pthread_mutex_unlock(self->mutex);
return 0;
2023-07-29 06:28:33 -04:00
}
2024-02-11 01:09:21 -05:00
haggis_job* haggis_jobq_pop(haggis_jobq *self) {
2023-07-29 06:28:33 -04:00
haggis_jobq_node *j;
haggis_job *job;
2023-07-29 06:28:33 -04:00
2024-02-11 01:09:21 -05:00
while (self->count == 0)
pthread_cond_wait(self->cond, self->mutex);
pthread_mutex_lock(self->mutex);
self->count--;
j = self->head;
job = j->job;
2024-02-11 01:09:21 -05:00
if (self->tail == self->head) {
self->tail = self->head = NULL;
2023-07-29 06:28:33 -04:00
} else {
2024-02-11 01:09:21 -05:00
self->head = self->head->prev;
2023-07-29 06:28:33 -04:00
}
free(j);
2024-02-11 01:09:21 -05:00
pthread_mutex_unlock(self->mutex);
return job;
2023-07-29 06:28:33 -04:00
}