-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_kfifo_thread_safe.c
63 lines (56 loc) · 1.43 KB
/
test_kfifo_thread_safe.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
// Copyright (c) 2024 cheng-zhongliang. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#define _GNU_SOURCE
#include <assert.h>
#include <pthread.h>
#include <sched.h>
#include "kfifo.h"
void set_cpu_affinity(int cpu_no) {
pthread_t t = pthread_self();
cpu_set_t cpu;
CPU_ZERO(&cpu);
CPU_SET(cpu_no, &cpu);
assert(pthread_setaffinity_np(t, sizeof(cpu_set_t), &cpu) == 0);
}
void* producer_thread(void* arg) {
set_cpu_affinity(0);
_KFIFO(kfifo, int)* kfifo = arg;
int n = 0;
do {
if(KFIFO_FULL(kfifo)) {
continue;
}
int* nn = calloc(1, sizeof(int));
*nn = n;
KFIFO_ENQUEUE(kfifo, nn);
n++;
} while(n != 10000);
return NULL;
}
void* consumer_thread(void* arg) {
set_cpu_affinity(1);
_KFIFO(kfifo, int)* kfifo = arg;
int n = 0;
do {
if(KFIFO_EMPTY(kfifo)) {
continue;
}
int* nn;
KFIFO_DEQUEUE(kfifo, nn);
assert(*nn == n);
free(nn);
n++;
} while(n != 10000);
return NULL;
}
int main(void) {
_KFIFO(kfifo, int) kfifo;
KFIFO_INIT(&kfifo, 16);
pthread_t producer, consumer;
pthread_create(&producer, NULL, producer_thread, &kfifo);
pthread_create(&consumer, NULL, consumer_thread, &kfifo);
pthread_join(producer, NULL);
pthread_join(consumer, NULL);
return 0;
}