* sysdeps/unix/sysv/linux/m68k/sysdep.h (INLINE_SYSCALL): Don't
[glibc.git] / linuxthreads / Examples / ex5.c
blobd39d487603939cb7cba509b4a46755240ba7d1f1
1 /* The classic producer-consumer example, implemented with semaphores.
2 All integers between 0 and 9999 should be printed exactly twice,
3 once to the right of the arrow and once to the left. */
5 #include <stdio.h>
6 #include "pthread.h"
7 #include "semaphore.h"
9 #define BUFFER_SIZE 16
11 /* Circular buffer of integers. */
13 struct prodcons
15 int buffer[BUFFER_SIZE]; /* the actual data */
16 int readpos, writepos; /* positions for reading and writing */
17 sem_t sem_read; /* number of elements available for reading */
18 sem_t sem_write; /* number of locations available for writing */
21 /* Initialize a buffer */
23 static void
24 init (struct prodcons *b)
26 sem_init (&b->sem_write, 0, BUFFER_SIZE - 1);
27 sem_init (&b->sem_read, 0, 0);
28 b->readpos = 0;
29 b->writepos = 0;
32 /* Store an integer in the buffer */
34 static void
35 put (struct prodcons *b, int data)
37 /* Wait until buffer is not full */
38 sem_wait (&b->sem_write);
39 /* Write the data and advance write pointer */
40 b->buffer[b->writepos] = data;
41 b->writepos++;
42 if (b->writepos >= BUFFER_SIZE)
43 b->writepos = 0;
44 /* Signal that the buffer contains one more element for reading */
45 sem_post (&b->sem_read);
48 /* Read and remove an integer from the buffer */
50 static int
51 get (struct prodcons *b)
53 int data;
54 /* Wait until buffer is not empty */
55 sem_wait (&b->sem_read);
56 /* Read the data and advance read pointer */
57 data = b->buffer[b->readpos];
58 b->readpos++;
59 if (b->readpos >= BUFFER_SIZE)
60 b->readpos = 0;
61 /* Signal that the buffer has now one more location for writing */
62 sem_post (&b->sem_write);
63 return data;
66 /* A test program: one thread inserts integers from 1 to 10000,
67 the other reads them and prints them. */
69 #define OVER (-1)
71 struct prodcons buffer;
73 static void *
74 producer (void *data)
76 int n;
77 for (n = 0; n < 10000; n++)
79 printf ("%d --->\n", n);
80 put (&buffer, n);
82 put (&buffer, OVER);
83 return NULL;
86 static void *
87 consumer (void *data)
89 int d;
90 while (1)
92 d = get (&buffer);
93 if (d == OVER)
94 break;
95 printf ("---> %d\n", d);
97 return NULL;
101 main (void)
103 pthread_t th_a, th_b;
104 void *retval;
106 init (&buffer);
107 /* Create the threads */
108 pthread_create (&th_a, NULL, producer, 0);
109 pthread_create (&th_b, NULL, consumer, 0);
110 /* Wait until producer and consumer finish. */
111 pthread_join (th_a, &retval);
112 pthread_join (th_b, &retval);
113 return 0;