Update.
[glibc.git] / linuxthreads / Examples / ex2.c
blob70cb6b3986d6f89371e127c3c920f22e5ba18584
1 /* The classic producer-consumer example.
2 Illustrates mutexes and conditions.
3 All integers between 0 and 9999 should be printed exactly twice,
4 once to the right of the arrow and once to the left. */
6 #include <stdio.h>
7 #include "pthread.h"
9 #define BUFFER_SIZE 16
11 /* Circular buffer of integers. */
13 struct prodcons {
14 int buffer[BUFFER_SIZE]; /* the actual data */
15 pthread_mutex_t lock; /* mutex ensuring exclusive access to buffer */
16 int readpos, writepos; /* positions for reading and writing */
17 pthread_cond_t notempty; /* signaled when buffer is not empty */
18 pthread_cond_t notfull; /* signaled when buffer is not full */
21 /* Initialize a buffer */
23 void init(struct prodcons * b)
25 pthread_mutex_init(&b->lock, NULL);
26 pthread_cond_init(&b->notempty, NULL);
27 pthread_cond_init(&b->notfull, NULL);
28 b->readpos = 0;
29 b->writepos = 0;
32 /* Store an integer in the buffer */
34 void put(struct prodcons * b, int data)
36 pthread_mutex_lock(&b->lock);
37 /* Wait until buffer is not full */
38 while ((b->writepos + 1) % BUFFER_SIZE == b->readpos) {
39 pthread_cond_wait(&b->notfull, &b->lock);
40 /* pthread_cond_wait reacquired b->lock before returning */
42 /* Write the data and advance write pointer */
43 b->buffer[b->writepos] = data;
44 b->writepos++;
45 if (b->writepos >= BUFFER_SIZE) b->writepos = 0;
46 /* Signal that the buffer is now not empty */
47 pthread_cond_signal(&b->notempty);
48 pthread_mutex_unlock(&b->lock);
51 /* Read and remove an integer from the buffer */
53 int get(struct prodcons * b)
55 int data;
56 pthread_mutex_lock(&b->lock);
57 /* Wait until buffer is not empty */
58 while (b->writepos == b->readpos) {
59 pthread_cond_wait(&b->notempty, &b->lock);
61 /* Read the data and advance read pointer */
62 data = b->buffer[b->readpos];
63 b->readpos++;
64 if (b->readpos >= BUFFER_SIZE) b->readpos = 0;
65 /* Signal that the buffer is now not full */
66 pthread_cond_signal(&b->notfull);
67 pthread_mutex_unlock(&b->lock);
68 return data;
71 /* A test program: one thread inserts integers from 1 to 10000,
72 the other reads them and prints them. */
74 #define OVER (-1)
76 struct prodcons buffer;
78 void * producer(void * data)
80 int n;
81 for (n = 0; n < 10000; n++) {
82 printf("%d --->\n", n);
83 put(&buffer, n);
85 put(&buffer, OVER);
86 return NULL;
89 void * consumer(void * data)
91 int d;
92 while (1) {
93 d = get(&buffer);
94 if (d == OVER) break;
95 printf("---> %d\n", d);
97 return NULL;
100 int main(void)
102 pthread_t th_a, th_b;
103 void * retval;
105 init(&buffer);
106 /* Create the threads */
107 pthread_create(&th_a, NULL, producer, 0);
108 pthread_create(&th_b, NULL, consumer, 0);
109 /* Wait until producer and consumer finish. */
110 pthread_join(th_a, &retval);
111 pthread_join(th_b, &retval);
112 return 0;