kerrighan Carpe diem, seize the day... | Bonjour,
Je suis entrain d'essayer de faire un petit code mettant en oeuvre le schéma producteur / consommateur.
Le fonctionnement du programme est simple:
Le producteur incrémente une variable entière et le producteur affiche cette variable.
Le soucis c'est que j'ai une segmentation fault au moment de l'affichage et je n'arrive pas à trouver de solution
Code :
- #include <stdio.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <semaphore.h>
- // initialisation du mutex
- pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
- sem_t scons;
- sem_t sprod;
- int somme=0;
- int * p_somme;
- int temp;
- int * p_temp;
- void affichage(int * p_somme) {
- printf("%s\n",*p_somme);
- }
- void calcul(int * p_somme) {
- *p_somme = *p_somme + 1;
- p_temp = &somme;
- sleep(1);
- }
- //**********************************
- //Le consommateur
- //**********************************
- void mutex_cons (int somme)
- {
-
- for (;;)
- {
- sem_wait(&scons);
- pthread_mutex_lock(&m);
- affichage(p_somme);
- pthread_mutex_unlock(&m);
- sem_post(&sprod);
- }
- }
- //**********************************
- //Le producteur
- //**********************************
- char mutex_prod (int somme)
- {
- for (;;)
- {
- calcul(p_somme);
- sem_wait(&sprod);
- pthread_mutex_lock(&m);
- p_somme = p_temp;
- sem_post(&scons);
- pthread_mutex_unlock(&m);
-
- }
- }
-
- //**********************************
- //Le main du programme
- //**********************************
-
- int main(int argc, char * argv[])
- {
- p_somme = &somme;
- // Initialise les semaphores
- sem_init(&scons, 0, 0);
- sem_init(&sprod, 0, 1);
-
- // Cree les threads
- pthread_t tid_cons;
- pthread_t tid_prod;
-
- pthread_create(&tid_prod, NULL, mutex_prod,p_somme);
- pthread_create(&tid_cons, NULL, mutex_cons,p_somme);
-
- // termine les threads
- int ret;
- pthread_join(tid_cons, &ret);
- printf("Retour thread conso n%d = %d \n", tid_cons, ret);
- pthread_join(tid_prod, &ret);
- printf("Retour thread prod n%d = %d \n", tid_prod, ret);
-
- return 0;
- }
- //fin main
|
|