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
104
105
106
|
/*
tfifo.c
David Rowe
Nov 19 2012
Tests FIFOs, in particular thread safety.
*/
#include <assert.h>
#include <stdio.h>
#include <pthread.h>
#include "codec2_fifo.h"
#define FIFO_SZ 1024
#define WRITE_SZ 10
#define READ_SZ 8
#define N_MAX 100
#define LOOPS 1000000
int run_thread = 1;
struct FIFO *f;
void writer(void);
void *writer_thread(void *data);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
#define USE_THREADS
//#define USE_MUTEX
int main() {
pthread_t awriter_thread;
int i,j;
short read_buf[READ_SZ];
int n_out = 0;
int success;
f = codec2_fifo_create(FIFO_SZ);
#ifdef USE_THREADS
pthread_create(&awriter_thread, NULL, writer_thread, NULL);
#endif
for(i=0; i<LOOPS; ) {
#ifndef USE_THREADS
writer();
#endif
#ifdef USE_MUTEX
pthread_mutex_lock(&mutex);
#endif
success = (codec2_fifo_read(f, read_buf, READ_SZ) == 0);
#ifdef USE_MUTEX
pthread_mutex_unlock(&mutex);
#endif
if (success) {
for(j=0; j<READ_SZ; j++) {
if (read_buf[j] != n_out) {
printf("error: %d %d\n", read_buf[j], n_out);
return(1);
}
n_out++;
if (n_out == N_MAX)
n_out = 0;
}
i++;
}
}
#ifdef USE_THREADS
run_thread = 0;
pthread_join(awriter_thread,NULL);
#endif
printf("%d loops tested OK\n", LOOPS);
return 0;
}
int n_in = 0;
void writer(void) {
short write_buf[WRITE_SZ];
int i;
if ((FIFO_SZ - codec2_fifo_used(f)) > WRITE_SZ) {
for(i=0; i<WRITE_SZ; i++) {
write_buf[i] = n_in++;
if (n_in == N_MAX)
n_in = 0;
}
#ifdef USE_MUTEX
pthread_mutex_lock(&mutex);
#endif
codec2_fifo_write(f, write_buf, WRITE_SZ);
pthread_mutex_unlock(&mutex);
}
}
void *writer_thread(void *data) {
while(run_thread) {
writer();
}
return NULL;
}
|