1 /*
2 tfifo.c
3 David Rowe
4 Nov 19 2012
5
6 Tests FIFOs, in particular thread safety.
7 */
8
9 #include <assert.h>
10 #include <stdio.h>
11 #include <pthread.h>
12 #include "codec2_fifo.h"
13
14 #define FIFO_SZ 1024
15 #define WRITE_SZ 10
16 #define READ_SZ 8
17 #define N_MAX 100
18 #define LOOPS 1000000
19
20 int run_thread = 1;
21 struct FIFO *f;
22
23 void writer(void);
24 void *writer_thread(void *data);
25 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
26
27 #define USE_THREADS
28 //#define USE_MUTEX
29
main()30 int main() {
31 pthread_t awriter_thread;
32 int i,j;
33 short read_buf[READ_SZ];
34 int n_out = 0;
35 int success;
36
37 f = codec2_fifo_create(FIFO_SZ);
38 #ifdef USE_THREADS
39 pthread_create(&awriter_thread, NULL, writer_thread, NULL);
40 #endif
41
42 for(i=0; i<LOOPS; ) {
43 #ifndef USE_THREADS
44 writer();
45 #endif
46
47 #ifdef USE_MUTEX
48 pthread_mutex_lock(&mutex);
49 #endif
50 success = (codec2_fifo_read(f, read_buf, READ_SZ) == 0);
51 #ifdef USE_MUTEX
52 pthread_mutex_unlock(&mutex);
53 #endif
54
55 if (success) {
56 for(j=0; j<READ_SZ; j++) {
57 if (read_buf[j] != n_out) {
58 printf("error: %d %d\n", read_buf[j], n_out);
59 return(1);
60 }
61 n_out++;
62 if (n_out == N_MAX)
63 n_out = 0;
64 }
65 i++;
66 }
67
68 }
69
70 #ifdef USE_THREADS
71 run_thread = 0;
72 pthread_join(awriter_thread,NULL);
73 #endif
74
75 printf("%d loops tested OK\n", LOOPS);
76 return 0;
77 }
78
79 int n_in = 0;
80
writer(void)81 void writer(void) {
82 short write_buf[WRITE_SZ];
83 int i;
84
85 if ((FIFO_SZ - codec2_fifo_used(f)) > WRITE_SZ) {
86 for(i=0; i<WRITE_SZ; i++) {
87 write_buf[i] = n_in++;
88 if (n_in == N_MAX)
89 n_in = 0;
90 }
91 #ifdef USE_MUTEX
92 pthread_mutex_lock(&mutex);
93 #endif
94 codec2_fifo_write(f, write_buf, WRITE_SZ);
95 pthread_mutex_unlock(&mutex);
96 }
97 }
98
writer_thread(void * data)99 void *writer_thread(void *data) {
100
101 while(run_thread) {
102 writer();
103 }
104
105 return NULL;
106 }
107