1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h>
#define MAX 256
char *buffer; sem_t empty; sem_t full; sem_t mutex;
void* producer(void *arg) { while (1) { sem_wait(&empty); sem_wait(&mutex); printf("input something to buffer: "); buffer = (char *)malloc(MAX); fgets(buffer, MAX, stdin); sem_post(&mutex); sem_post(&full); sleep(1); } }
void* consumer(void *arg) { while (1) { sem_wait(&full); sem_wait(&mutex); printf("read product from buffer: %s", buffer); memset(buffer, 0, MAX); free(buffer); sem_post(&mutex); sem_post(&empty); sleep(1); } }
int main() { pthread_t id_producer, id_consumer; int ret;
sem_init(&empty, 0, 10); sem_init(&full, 0, 0); sem_init(&mutex, 0, 1);
ret = pthread_create(&id_producer, NULL, producer, NULL); if (ret != 0) { printf("Producer creation failed\n"); exit(1); }
ret = pthread_create(&id_consumer, NULL, consumer, NULL); if (ret != 0) { printf("Consumer creation failed\n"); exit(1); }
pthread_join(id_producer, NULL); pthread_join(id_consumer, NULL);
sem_destroy(&empty); sem_destroy(&full); sem_destroy(&mutex);
printf("The End...\n"); return 0; }
|