1 | /* Copyright (C) 2008, 2014 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 %p\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 %p\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 |
|
---|
57 | while (count == N) pthread_cond_wait(&full, &lock);
|
---|
58 | printf("Buffer a %d\n", count);
|
---|
59 | buffer[count++] = o;
|
---|
60 | if (count == 1) pthread_cond_signal(&empty);
|
---|
61 |
|
---|
62 | pthread_mutex_unlock(&lock);
|
---|
63 | }
|
---|
64 |
|
---|
65 | /* passaggio per indirizzo per evitare di fare la return fuori dai lock */
|
---|
66 | void b_remove(char** result)
|
---|
67 | {
|
---|
68 | pthread_mutex_lock(&lock);
|
---|
69 |
|
---|
70 | while (count == 0) pthread_cond_wait(&empty, &lock);
|
---|
71 | printf("Buffer a %d\n", count);
|
---|
72 | *result = buffer[--count];
|
---|
73 | if (count == N-1) pthread_cond_signal(&full);
|
---|
74 |
|
---|
75 | pthread_mutex_unlock(&lock);
|
---|
76 | }
|
---|
77 |
|
---|
78 |
|
---|
79 | /* Local Variables: */
|
---|
80 | /* compile-command: "make -k " */
|
---|
81 | /* End: */
|
---|
82 |
|
---|
83 |
|
---|