1 /* -*- c-basic-offset: 4 -*-  vi:set ts=8 sts=4 sw=4: */
2 
3 /* message_buffer.c
4 
5    This file is in the public domain.
6 */
7 
8 #include <unistd.h>
9 #include <string.h>
10 #include <pthread.h>
11 #include <stdio.h>
12 
13 #define BUFFERS      16		/* must be 2^n */
14 #define BUFFER_SIZE 256
15 
16 static char buffer[BUFFERS][BUFFER_SIZE];
17 static const char *mb_prefix;
18 static unsigned int initialised = 0;
19 static unsigned int in_buffer = 0;
20 static unsigned int out_buffer = 0;
21 static pthread_t writer_thread;
22 
23 void *mb_thread_func(void *arg);
24 
add_message(const char * msg)25 void add_message(const char *msg)
26 {
27     strncpy(buffer[in_buffer], msg, BUFFER_SIZE - 1);
28     in_buffer = (in_buffer + 1) & (BUFFERS - 1);
29 }
30 
mb_init(const char * prefix)31 void mb_init(const char *prefix)
32 {
33     if (initialised) {
34 	return;
35     }
36     mb_prefix = prefix;
37 
38     pthread_create(&writer_thread, NULL, &mb_thread_func, NULL);
39 
40     initialised = 1;
41 }
42 
mb_thread_func(void * arg)43 void *mb_thread_func(void *arg)
44 {
45     while (1) {
46 	while (out_buffer != in_buffer) {
47 	    printf("%s%s", mb_prefix, buffer[out_buffer]);
48 	    out_buffer = (out_buffer + 1) & (BUFFERS - 1);
49 	}
50 	usleep(1000);
51     }
52 
53     return NULL;
54 }
55 
56 /* vi:set ts=8 sts=4 sw=4: */
57