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. */
11 /* Circular buffer of integers. */
15 int buffer
[BUFFER_SIZE
]; /* the actual data */
16 pthread_mutex_t lock
; /* mutex ensuring exclusive access to buffer */
17 int readpos
, writepos
; /* positions for reading and writing */
18 pthread_cond_t notempty
; /* signaled when buffer is not empty */
19 pthread_cond_t notfull
; /* signaled when buffer is not full */
22 /* Initialize a buffer */
24 init (struct prodcons
*b
)
26 pthread_mutex_init (&b
->lock
, NULL
);
27 pthread_cond_init (&b
->notempty
, NULL
);
28 pthread_cond_init (&b
->notfull
, NULL
);
33 /* Store an integer in the buffer */
35 put (struct prodcons
*b
, int data
)
37 pthread_mutex_lock (&b
->lock
);
38 /* Wait until buffer is not full */
39 while ((b
->writepos
+ 1) % BUFFER_SIZE
== b
->readpos
)
41 pthread_cond_wait (&b
->notfull
, &b
->lock
);
42 /* pthread_cond_wait reacquired b->lock before returning */
44 /* Write the data and advance write pointer */
45 b
->buffer
[b
->writepos
] = data
;
47 if (b
->writepos
>= BUFFER_SIZE
)
49 /* Signal that the buffer is now not empty */
50 pthread_cond_signal (&b
->notempty
);
51 pthread_mutex_unlock (&b
->lock
);
54 /* Read and remove an integer from the buffer */
56 get (struct prodcons
*b
)
59 pthread_mutex_lock (&b
->lock
);
60 /* Wait until buffer is not empty */
61 while (b
->writepos
== b
->readpos
)
63 pthread_cond_wait (&b
->notempty
, &b
->lock
);
65 /* Read the data and advance read pointer */
66 data
= b
->buffer
[b
->readpos
];
68 if (b
->readpos
>= BUFFER_SIZE
)
70 /* Signal that the buffer is now not full */
71 pthread_cond_signal (&b
->notfull
);
72 pthread_mutex_unlock (&b
->lock
);
76 /* A test program: one thread inserts integers from 1 to 10000,
77 the other reads them and prints them. */
81 struct prodcons buffer
;
87 for (n
= 0; n
< 10000; n
++)
89 printf ("%d --->\n", n
);
105 printf ("---> %d\n", d
);
113 pthread_t th_a
, th_b
;
117 /* Create the threads */
118 pthread_create (&th_a
, NULL
, producer
, 0);
119 pthread_create (&th_b
, NULL
, consumer
, 0);
120 /* Wait until producer and consumer finish. */
121 pthread_join (th_a
, &retval
);
122 pthread_join (th_b
, &retval
);