81 lines
3 KiB
C
81 lines
3 KiB
C
![]() |
/* _,.---._ .-._ .--.-. ,--.--------.
|
||
|
* _,..---._ ,-.' , - `. /==/ \ .-._/==/ //==/, - , -\
|
||
|
* /==/, - \ /==/_, , - \|==|, \/ /, |==\ -\\==\.-. - ,-./
|
||
|
* |==| _ _\==| .=. |==|- \| | \==\- \`--`\==\- \
|
||
|
* |==| .=. |==|_ : ;=: - |==| , | -| `--`-' \==\_ \
|
||
|
* |==|,| | -|==| , '=' |==| - _ | |==|- |
|
||
|
* |==| '=' /\==\ - ,_ /|==| /\ , | |==|, |
|
||
|
* |==|-, _`/ '.='. - .' /==/, | |- | /==/ -/
|
||
|
* `-.`.____.' `--`--'' `--`./ `--` `--`--`
|
||
|
* _ __ ,---. .-._ .=-.-. _,.----.
|
||
|
* .-`.' ,`..--.' \ /==/ \ .-._ /==/_ /.' .' - \
|
||
|
* /==/, - \==\-/\ \ |==|, \/ /, /==|, |/==/ , ,-'
|
||
|
* |==| _ .=. /==/-|_\ | |==|- \| ||==| ||==|- | .
|
||
|
* |==| , '=',\==\, - \ |==| , | -||==|- ||==|_ `-' \
|
||
|
* |==|- '..'/==/ - ,| |==| - _ ||==| ,||==| _ , |
|
||
|
* |==|, | /==/- /\ - \|==| /\ , ||==|- |\==\. /
|
||
|
* /==/ - | \==\ _.\=\.-'/==/, | |- |/==/. / `-.`.___.-'
|
||
|
* `--`---' `--` `--`./ `--``--`-`
|
||
|
*
|
||
|
* @(#)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
|
||
|
|
||
|
#include "mq.h"
|
||
|
|
||
|
haggis_msg* haggis_msg_init(haggis_message_type tag, haggis_message_body body) {
|
||
|
haggis_msg *msg = calloc(1, sizeof(haggis_msg));
|
||
|
if (msg == NULL)
|
||
|
return NULL;
|
||
|
msg->next = msg->prev = NULL;
|
||
|
msg->tag = tag;
|
||
|
msg->body = body;
|
||
|
return msg;
|
||
|
}
|
||
|
|
||
|
int haggis_mq_push(haggis_mq *queue, haggis_msg *msg) {
|
||
|
msg->next = msg->prev = NULL;
|
||
|
|
||
|
pthread_mutex_lock(queue->mutex);
|
||
|
if (queue->tail == NULL) {
|
||
|
queue->tail = queue->head = msg;
|
||
|
} else {
|
||
|
msg->next = queue->tail;
|
||
|
queue->tail->prev = msg;
|
||
|
queue->tail = msg;
|
||
|
}
|
||
|
queue->count++;
|
||
|
pthread_mutex_unlock(queue->mutex);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
haggis_msg* haggis_mq_pop(haggis_mq *queue) {
|
||
|
haggis_msg *msg;
|
||
|
|
||
|
while (queue->count == 0)
|
||
|
pthread_cond_wait(queue->cond, queue->mutex);
|
||
|
pthread_mutex_lock(queue->mutex);
|
||
|
queue->count--;
|
||
|
msg = queue->head;
|
||
|
if (msg->tag == EndOfArchive)
|
||
|
return NULL;
|
||
|
if (queue->tail == queue->head) {
|
||
|
queue->tail = queue->head = NULL;
|
||
|
} else {
|
||
|
queue->head = queue->head->prev;
|
||
|
}
|
||
|
pthread_mutex_unlock(queue->mutex);
|
||
|
msg->prev = msg->next = NULL;
|
||
|
return msg;
|
||
|
}
|