ArchiSys/TD/TD9/exercice1.c
2024-04-19 08:11:16 +02:00

70 lines
1.3 KiB
C

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <limits.h>
#include <stdbool.h>
#define N 50
//#define SHOW_DETAILS
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void* access_res(void* args) {
int id = *(int*)args;
*(int*)args = 0;
for (int i=0; i < INT_MAX; i++) {
pthread_mutex_lock(&lock);
*(int*)args += 1;
pthread_mutex_unlock(&lock);
}
*(int*)args = -1;
return NULL;
}
int main() {
pthread_t tid[N];
int args[N]; // Reuse it for the number of accesses
for (int i=0; i < N; i++) {
args[i] = i;
pthread_create(&(tid[i]), NULL, &access_res, (void*)&(args[i]));
}
bool is_end = false;
while (!is_end) {
#ifdef SHOW_DETAILS
printf("Accesses:\n");
#endif
int max, min, avg;
max = avg = 0;
min = INT_MAX;
for (int i=0; i < N; i++) {
#ifdef SHOW_DETAILS
printf("%d ", args[i]);
#endif
if (args[i] == -1)
is_end = true;
if (args[i] > max)
max = args[i];
if (args[i] < min)
min = args[i];
avg += args[i]/N;
}
#ifdef SHOW_DETAILS
printf("\n");
#endif
printf("min max avg : %d %d %d\n", min, max, avg);
sleep(1);
}
for (int i=0; i < N; i++) {
pthread_join(tid[i], NULL);
}
}