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
96
97
98
99
100
101
102
103
|
#include "arena.h"
#include "ll.h"
#include "encryption.h"
#include "scanner.h"
#include "shared.h"
#include "threadpool.h"
#include <errno.h>
#include <error.h>
#include <threads.h>
#include <unistd.h>
#include <string.h>
typedef int (*thingcb)(void*);
struct thing {
thingcb cb;
void *arg;
};
typedef struct queue {
mtx_t *cqmutex;
cnd_t *cqcnd;
unsigned char cstatus;
int len;
int used;
struct thing **queue;
} ccqueue;
#define QUEUE_LEN 10
int consumer(void *queue) {
if(!queue)
thrd_exit(-1);
ccqueue *real = (ccqueue *)queue;
for(struct thing *thing = NULL;;) {
cnd_wait(real->cqcnd, real->cqmutex);
if(real->cstatus)
thrd_exit(-1);
if(real->used > 0) {
thing = real->queue[real->used - 1];
real->used--;
}
if(thing != NULL)
if(thing->arg != NULL)
thing->cb(thing->arg);
}
thrd_exit(0);
}
int testcb(void *data) {
if(!data)
return -1;
printf("%s\n", (char*)data);
return 0;
}
int main() {
// error(1, ENOTSUP, "No main file lol");
// Manually implement a threadpool and consumer in a "dumb" way to make sure I'm doing the correct thing
ccqueue *cqueue = xcalloc(1, sizeof(*cqueue));
cqueue->cqmutex = xcalloc(1, sizeof(*cqueue->cqmutex)); mtx_init(cqueue->cqmutex, mtx_plain);
cqueue->cqcnd = xcalloc(1, sizeof(*cqueue->cqcnd)); cnd_init(cqueue->cqcnd);
cqueue->cstatus = 0;
cqueue->len = QUEUE_LEN;
cqueue->used = 0;
cqueue->queue = xcalloc(cqueue->len, sizeof(struct thing *));
thrd_t *thread = xcalloc(1, sizeof(*thread));
thrd_create(thread, consumer, (void *)cqueue);
mtx_lock(cqueue->cqmutex);
cqueue->queue[cqueue->used] = xcalloc(1, sizeof(struct thing));
cqueue->queue[cqueue->used]->cb = testcb;
cqueue->queue[cqueue->used]->arg = "This is some data";
cqueue->used++;
mtx_unlock(cqueue->cqmutex);
cnd_signal(cqueue->cqcnd);
sleep(1);
mtx_lock(cqueue->cqmutex);
cqueue->cstatus++;
mtx_unlock(cqueue->cqmutex);
cnd_broadcast(cqueue->cqcnd);
// Destroy and free everything
mtx_destroy(cqueue->cqmutex); cnd_destroy(cqueue->cqcnd);
free(cqueue->cqmutex); free(cqueue->cqcnd);
free(cqueue->queue);
free(cqueue);
return 0;
}
// Ok well now I'm pissed. The canceling works fine but it's not actually consuming the thing
|