source: trunk/pthreads-pc.c@ 3

Last change on this file since 3 was 2, checked in by Mattia Monga, 13 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
7void b_insert(char*);
8void b_remove(char**);
9
10
11void* 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
21void* 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
32int 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
46char* buffer[N];
47int count = 0;
48
49pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
50pthread_cond_t full = PTHREAD_COND_INITIALIZER;
51pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
52
53void 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 */
65void 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.