[2] | 1 | /* Copyright (C) 2008 by Mattia Monga <mattia.monga@unimi.it> */
|
---|
| 2 | /* $Id$ */
|
---|
| 3 | #include <pthread.h>
|
---|
| 4 | #include <stdio.h>
|
---|
| 5 | #include <stdlib.h>
|
---|
| 6 |
|
---|
| 7 | void b_insert(char*);
|
---|
| 8 | void b_remove(char**);
|
---|
| 9 |
|
---|
| 10 |
|
---|
| 11 | void* producer(void* args)
|
---|
| 12 | {
|
---|
| 13 | while (1){
|
---|
| 14 | char* o = (char*)malloc(sizeof(char));
|
---|
| 15 | printf("Ho prodotto %x\n", o);
|
---|
| 16 | b_insert(o);
|
---|
| 17 | }
|
---|
| 18 | return NULL;
|
---|
| 19 | }
|
---|
| 20 |
|
---|
| 21 | void* consumer(void* args)
|
---|
| 22 | {
|
---|
| 23 | while (1){
|
---|
| 24 | char* o;
|
---|
| 25 | b_remove(&o);
|
---|
| 26 | free(o);
|
---|
| 27 | printf("Ho consumato %x\n", o);
|
---|
| 28 | }
|
---|
| 29 | return NULL;
|
---|
| 30 | }
|
---|
| 31 |
|
---|
| 32 | int main(void){
|
---|
| 33 |
|
---|
| 34 | pthread_t p, c;
|
---|
| 35 |
|
---|
| 36 |
|
---|
| 37 | pthread_create(&p, NULL, &producer, NULL);
|
---|
| 38 | pthread_create(&c, NULL, &consumer, NULL);
|
---|
| 39 |
|
---|
| 40 | pthread_join(p, NULL);
|
---|
| 41 | pthread_join(c, NULL);
|
---|
| 42 | return 0;
|
---|
| 43 | }
|
---|
| 44 |
|
---|
| 45 | #define N 10
|
---|
| 46 | char* buffer[N];
|
---|
| 47 | int count = 0;
|
---|
| 48 |
|
---|
| 49 | pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
---|
| 50 | pthread_cond_t full = PTHREAD_COND_INITIALIZER;
|
---|
| 51 | pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
|
---|
| 52 |
|
---|
| 53 | void b_insert(char* o)
|
---|
| 54 | {
|
---|
| 55 | pthread_mutex_lock(&lock);
|
---|
| 56 |
|
---|
[8] | 57 | while (count == N) pthread_cond_wait(&full, &lock);
|
---|
[2] | 58 | buffer[count++] = o;
|
---|
| 59 | if (count == 1) pthread_cond_signal(&empty);
|
---|
| 60 |
|
---|
| 61 | pthread_mutex_unlock(&lock);
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | /* passaggio per indirizzo per evitare di fare la return fuori dai lock */
|
---|
| 65 | void b_remove(char** result)
|
---|
| 66 | {
|
---|
| 67 | pthread_mutex_lock(&lock);
|
---|
| 68 |
|
---|
[8] | 69 | while (count == 0) pthread_cond_wait(&empty, &lock);
|
---|
[2] | 70 | *result = buffer[--count];
|
---|
| 71 | if (count == N-1) pthread_cond_signal(&full);
|
---|
| 72 |
|
---|
| 73 | pthread_mutex_unlock(&lock);
|
---|
| 74 | }
|
---|
| 75 |
|
---|
| 76 |
|
---|
| 77 | /* Local Variables: */
|
---|
| 78 | /* compile-command: "make -k " */
|
---|
| 79 | /* End: */
|
---|
| 80 |
|
---|
| 81 |
|
---|