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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <pthread.h>
#include <time.h>
#include <unistd.h>
#include <semaphore.h>
sem_t sem;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int compteur = 0;
void *fonction_thread_1(void *);
int main(int argc, char const *argv[])
{
/* code */
if ((argc != 2) || (atoi(argv[1]) < 0))
{
fprintf(stderr, "Usage: %s un_nombre_entier_positif\n", argv[0]);
exit(EXIT_FAILURE);
}
srand(time(NULL));
int nbre_thread = atoi(argv[1]), retour[nbre_thread];
pthread_t id_thread[nbre_thread];
sem_init(&sem, 0, 2);
for (int i = 0; i < nbre_thread; i++)
{
/* code */
retour[i] = pthread_create(&id_thread[i], NULL, fonction_thread_1, (void*)(intptr_t)i);
if (retour[i] == -1)
printf("Erreur lors de la création du thread %d!!\n", i);
}
for (int i = 0; i < nbre_thread; i++)
{
/* code */
pthread_join(id_thread[i], NULL);
}
pthread_mutex_destroy(&mutex);
sem_destroy(&sem);
return 0;
}
void *fonction_thread_1(void *arg)
{
while (1)
{
/* code */
int sec = rand() % 5 + 1, num_thread = (intptr_t)arg;
pthread_mutex_lock(&mutex);
sem_wait(&sem);
pthread_mutex_unlock(&mutex);
printf("Le thread %d entre en section critique pour %d secondes.\n", num_thread, sec);
sleep(sec);
pthread_mutex_lock(&mutex);
sem_post(&sem);
pthread_mutex_unlock(&mutex);
printf("Le thread %d sort de la section critique.\n", num_thread);
if(compteur == 10)
break;
pthread_mutex_lock(&mutex);
compteur++;
pthread_mutex_unlock(&mutex);
}
pthread_exit(NULL);
} |
Partager