aboutsummaryrefslogtreecommitdiff
path: root/src/messages.c
blob: 1c1378e13e2465fc0c7df8daba59596161da09f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include "messages.h"

int mqueue_get(MessageQueue *q, SynthMessage *msg) {
  pthread_mutex_lock(&(q)->lock);
  if ((q)->tail == (q)->head) {
	pthread_mutex_unlock(&(q)->lock);
	return 1;
  }

  *(msg) = (q)->buffer[(q)->tail];
  (q)->tail = ((q)->tail + 1) % MESSAGE_QUEUE_SIZE;

  pthread_mutex_unlock(&(q)->lock);
  return 0;
}

int mqueue__push_no_lock(MessageQueue *q, SynthMessage msg) {
  size_t next = ((q)->head + 1) % MESSAGE_QUEUE_SIZE;

  if ((q)->tail == next) {
	return 1;
  }

  (q)->buffer[(q)->head] = msg;
  (q)->head = next;
  return 0;
}

int mqueue_push(MessageQueue *q, SynthMessage msg) {
  pthread_mutex_lock(&(q)->lock);
  int ret = mqueue__push_no_lock(q, msg);
  pthread_mutex_unlock(&(q)->lock);
  return ret;
}

int mqueue_push_many(MessageQueue *q, SynthMessage *msg, size_t count) {
  pthread_mutex_lock(&(q)->lock);
  int ret = 0;
  for (size_t i = 0; i < count; i++) {
	ret = mqueue__push_no_lock(q, msg[i]);
	if (ret != 0) {
	  break;
	}
  }
  pthread_mutex_unlock(&(q)->lock);
  return ret;
}