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. */
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
);
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
;
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
)
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
];
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
);
71 /* A test program: one thread inserts integers from 1 to 10000,
72 the other reads them and prints them. */
76 struct prodcons buffer
;
78 void * producer(void * data
)
81 for (n
= 0; n
< 10000; n
++) {
82 printf("%d --->\n", n
);
89 void * consumer(void * data
)
95 printf("---> %d\n", d
);
102 pthread_t th_a
, th_b
;
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
);