-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_queue.c
More file actions
74 lines (64 loc) · 1.52 KB
/
event_queue.c
File metadata and controls
74 lines (64 loc) · 1.52 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <pthread.h>
#include <stdbool.h>
#include <stdlib.h>
#include "event_queue.h"
#ifndef QUEUE_CAPACITY
#define QUEUE_CAPACITY 32
#endif
typedef struct {
event queue[QUEUE_CAPACITY];
int in;
int out;
pthread_mutex_t mtx;
pthread_cond_t cond;
bool quit;
} queue;
static queue q = {.in = 0, .out = 0};
void queue_init(void) {
pthread_mutex_init(&(q.mtx), NULL);
pthread_cond_init(&(q.cond), NULL);
}
void queue_cleanup(void) {
while (q.in != q.out) {
event ev = queue_pop();
if (ev.data.msg) {
free(ev.data.msg);
}
}
}
event queue_pop(void) {
event ev = {.type = EV_TYPE_NUM};
pthread_mutex_lock(&(q.mtx));
while (!q.quit && q.in == q.out) {
pthread_cond_wait(&(q.cond), &(q.mtx));
}
if (q.in != q.out) {
ev = q.queue[q.out];
q.out = (q.out + 1) % QUEUE_CAPACITY;
pthread_cond_broadcast(&(q.cond));
}
pthread_mutex_unlock(&(q.mtx));
return ev;
}
void queue_push(event ev) {
pthread_mutex_lock(&(q.mtx));
while (((q.in + 1) % QUEUE_CAPACITY) == q.out) {
pthread_cond_wait(&(q.cond), &(q.mtx));
}
q.queue[q.in] = ev;
q.in = (q.in + 1) % QUEUE_CAPACITY;
pthread_cond_broadcast(&(q.cond));
pthread_mutex_unlock(&(q.mtx));
}
bool is_quit() {
bool quit;
pthread_mutex_lock(&(q.mtx));
quit = q.quit;
pthread_mutex_unlock(&(q.mtx));
return quit;
}
void set_quit() {
pthread_mutex_lock(&(q.mtx));
q.quit = true;
pthread_mutex_unlock(&(q.mtx));
}