source: trunk/pthreads-pc.c @ 26

Last change on this file since 26 was 26, checked in by monga, 6 years ago

Programmi 2014

File size: 1.5 KB
Line 
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
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 %p\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 %p\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  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 */
66void 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
Note: See TracBrowser for help on using the repository browser.