Last change
on this file since 20 was 2, checked in by Mattia Monga, 14 years ago |
Importazione sorgenti
|
File size:
1.4 KB
|
Line | |
---|
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 | #include <sys/wait.h>
|
---|
7 |
|
---|
8 | void b_insert(char*);
|
---|
9 | void b_remove(char**);
|
---|
10 |
|
---|
11 |
|
---|
12 | void producer(void)
|
---|
13 | {
|
---|
14 | while (1){
|
---|
15 | char* o = (char*)malloc(sizeof(char));
|
---|
16 | printf("Ho prodotto %x\n", o);
|
---|
17 | b_insert(o);
|
---|
18 | }
|
---|
19 | }
|
---|
20 |
|
---|
21 | void consumer(void)
|
---|
22 | {
|
---|
23 | while (1){
|
---|
24 | char* o;
|
---|
25 | b_remove(&o);
|
---|
26 | free(o);
|
---|
27 | printf("Ho consumato %x\n", o);
|
---|
28 | }
|
---|
29 | }
|
---|
30 |
|
---|
31 | int main(void){
|
---|
32 |
|
---|
33 | int p, c;
|
---|
34 |
|
---|
35 | p = fork();
|
---|
36 | if (p == 0) producer();
|
---|
37 | c = fork();
|
---|
38 | if (c == 0) consumer();
|
---|
39 |
|
---|
40 | waitpid(-1, NULL, 0);
|
---|
41 |
|
---|
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 | if (count == N) pthread_cond_wait(&full, &lock);
|
---|
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 |
|
---|
69 | if (count == 0) pthread_cond_wait(&empty, &lock);
|
---|
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 |
|
---|
Note:
See
TracBrowser
for help on using the repository browser.