- pourquoi doit on declarer pthread_mutex_t en static dans le code suivant (dans les premières lignes)
- que se passe t -il si on enlève static, quels sont les risques encourus ?
merci d'avance
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
 
 
#include <stdlib.h>
#include <pthread.h>
 
static pthread_mutex_t my_mutex;
static int tab[5];
 
void *read_tab_process (void * arg)
{
  int i;
 
  pthread_mutex_lock (&my_mutex);
  for (i = 0 ; i != 5 ; i++)
    printf ("read_process, tab[%d] vaut %d\n", i, tab[i]);
  pthread_mutex_unlock (&my_mutex);
  pthread_exit (0);
}
 
void *write_tab_process (void * arg)
{
  int i;
 
  pthread_mutex_lock (&my_mutex);
  for (i = 0 ; i != 5 ; i++) {
    tab[i] = 2 * i;
    printf ("write_process, tab[%d] vaut %d\n", i, tab[i]);
    sleep (1); /* Relentit le thread d'ecriture... */
  }
  pthread_mutex_unlock (&my_mutex);
  pthread_exit (0);
}
 
main (int ac, char **av)
{
  pthread_t th1, th2;
  void *ret;
 
  pthread_mutex_init (&my_mutex, NULL);
 
  if (pthread_create (&th1, NULL, write_tab_process, NULL) < 0) {
    fprintf (stderr, "pthread_create error for thread 1\n");
    exit (1);
  }
 
  if (pthread_create (&th2, NULL, read_tab_process, NULL) < 0) {
    fprintf (stderr, "pthread_create error for thread 2\n");
    exit (1);
  }
 
  (void)pthread_join (th1, &ret);
  (void)pthread_join (th2, &ret);
}