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// SPDX-FileCopyrightText: 2012-2023 Brian Watling <brian@oxbo.dev>
// SPDX-License-Identifier: MIT
#include <mpmc_lifo.h>
#include <pthread.h>
#include <stdint.h>
#include <unistd.h>
#include "test_helper.h"
#define NUM_THREADS 4
#define PER_THREAD_COUNT 250000
int pushes[NUM_THREADS] = {};
int pops[NUM_THREADS] = {};
int volatile done[NUM_THREADS] = {};
pthread_barrier_t barrier;
mpmc_lifo_t the_q;
void* push_func(void* p) {
pthread_barrier_wait(&barrier);
intptr_t thr = (intptr_t)p;
intptr_t i = 0;
while (!done[thr]) {
++i;
mpmc_lifo_node_t* n = malloc(sizeof(mpmc_lifo_node_t));
n->data = (void*)i;
mpmc_lifo_push(&the_q, n);
}
return NULL;
}
void* pop_func(void* p) {
pthread_barrier_wait(&barrier);
intptr_t thr = (intptr_t)p;
intptr_t last = 0;
(void)last;
intptr_t counter = 0;
while (!done[thr]) {
mpmc_lifo_node_t* node = mpmc_lifo_pop(&the_q);
if (!node) {
usleep(1);
} else {
intptr_t i = (intptr_t)node->data;
if (NUM_THREADS == 1) {
assert(i > last);
last = i;
}
++counter;
if (counter > PER_THREAD_COUNT) {
done[thr] = 1;
}
free(node);
}
}
return NULL;
}
int main() {
pthread_barrier_init(&barrier, NULL, 2 * NUM_THREADS);
mpmc_lifo_init(&the_q);
pthread_t reader[NUM_THREADS];
pthread_t writer[NUM_THREADS];
int i;
for (i = 0; i < NUM_THREADS; ++i) {
pthread_create(&reader[i], NULL, &pop_func, (void*)(intptr_t)i);
}
for (i = 1; i < NUM_THREADS; ++i) {
pthread_create(&writer[i], NULL, &push_func, (void*)(intptr_t)i);
}
push_func(0);
for (i = 1; i < NUM_THREADS; ++i) {
pthread_join(reader[i], NULL);
}
for (i = 1; i < NUM_THREADS; ++i) {
pthread_join(writer[i], NULL);
}
return 0;
}