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. */
11 /* Circular buffer of integers. */
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 */
24 init (struct prodcons
*b
)
26 sem_init (&b
->sem_write
, 0, BUFFER_SIZE
- 1);
27 sem_init (&b
->sem_read
, 0, 0);
32 /* Store an integer in the buffer */
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
;
42 if (b
->writepos
>= BUFFER_SIZE
)
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 */
51 get (struct prodcons
*b
)
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
];
59 if (b
->readpos
>= BUFFER_SIZE
)
61 /* Signal that the buffer has now one more location for writing */
62 sem_post (&b
->sem_write
);
66 /* A test program: one thread inserts integers from 1 to 10000,
67 the other reads them and prints them. */
71 struct prodcons buffer
;
77 for (n
= 0; n
< 10000; n
++)
79 printf ("%d --->\n", n
);
95 printf ("---> %d\n", d
);
103 pthread_t th_a
, th_b
;
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
);