123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- #include "example2.h"
- void *produce(void *buf)
- {
- buffer *buff;
- buff = (buffer *) buf;
- printf("\nproducer started");
- for (int i = 0; i < 20; i++) {
- sem_wait(&buff->full);
- pthread_mutex_lock(&buff->mutex);
- buff->data[buff->pos] = 0;
- buff->pos = buff->pos + 1;
- printf("\nproduced");
- sem_post(&buff->empty);
- pthread_mutex_unlock(&buff->mutex);
- sleep(1);
- }
- pthread_exit(0);
- }
- void *consume(void *buf)
- {
- buffer *buff;
- buff = (buffer *) buf;
- printf("\nconsumer started");
- for (int i = 0; i < 20; i++) {
- sem_wait(&buff->empty);
- pthread_mutex_lock(&buff->mutex);
- buff->pos = buff->pos - 1;
- printf("\ngot value %d", buff->data[buff->pos]);
- printf("\nconsumed");
- sem_post(&buff->full);
- pthread_mutex_unlock(&buff->mutex);
- sleep(2);
- }
- pthread_exit(0);
- }
- void init_buffer(buffer * buf)
- {
- sem_init(&buf->empty, 0, 0);
- sem_init(&buf->full, 0, BUFFER_SIZE);
- pthread_mutex_init(&buf->mutex, NULL);
- buf->pos = 0;
- for (int i = 0; i < BUFFER_SIZE; i++) {
- buf->data[i] = -1;
- }
- }
|