-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchannels.c
95 lines (70 loc) · 2.11 KB
/
channels.c
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <pthread.h>
#include <stdlib.h>
typedef struct channel_t {
pthread_mutex_t mutex;
pthread_cond_t cond;
void** buffer;
unsigned int capacity;
unsigned int head;
unsigned int size;
char is_closed;
} channel;
channel* chan_create(unsigned int capacity) {
capacity += 1; // for the blocking send/rcv
channel* chan = malloc(sizeof(channel));
pthread_mutex_init(&chan->mutex, NULL);
pthread_cond_init(&chan->cond, NULL);
chan->buffer = malloc(sizeof(void*) * capacity);
chan->capacity = capacity;
chan->head = 0;
chan->size = 0;
chan->is_closed = 0;
return chan;
}
void chan_close(channel* chan) {
pthread_mutex_lock(&chan->mutex);
chan->is_closed = 1;
pthread_mutex_unlock(&chan->mutex);
}
void chan_destroy(channel* chan) {
chan_close(chan);
pthread_mutex_destroy(&chan->mutex);
pthread_cond_destroy(&chan->cond);
free(chan->buffer);
free(chan);
}
int chan_send(channel* chan, void* data) {
pthread_mutex_lock(&chan->mutex);
if(chan->is_closed) {
pthread_mutex_unlock(&chan->mutex);
return -1;
}
while(chan->size == chan->capacity) {
pthread_cond_wait(&chan->cond, &chan->mutex);
}
unsigned int index = (chan->head + chan->size) % chan->capacity;
chan->buffer[index] = data;
chan->size++;
pthread_cond_broadcast(&chan->cond);
while(chan->size == chan->capacity) {
pthread_cond_wait(&chan->cond, &chan->mutex);
}
pthread_mutex_unlock(&chan->mutex);
return 0;
}
int chan_recv(channel* chan, void** data) {
pthread_mutex_lock(&chan->mutex);
if(chan->size == 0 && chan->is_closed) {
pthread_mutex_unlock(&chan->mutex);
return -1;
}
while(chan->size == 0) {
pthread_cond_wait(&chan->cond, &chan->mutex);
}
*data = chan->buffer[chan->head];
chan->head = (chan->head + 1) % chan->capacity;
chan->size--;
pthread_cond_broadcast(&chan->cond);
pthread_mutex_unlock(&chan->mutex);
return 0;
}