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

85 lines
1.7 KiB
C

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define N 20
#define PROD 5
#define CONS 5
#define PROD_MAX 500
int shared_buffer[N];
void* producteur(void* args) {
int j, product = 0;
int count = 0;
while (1) {
int i = -1;
while (++i < N) {
if (shared_buffer[i] == -1) {
break;
}
}
if (i >= N) {
sleep(0.05);
continue;
}
product = (rand()%500+product)%20000;
j = (i+j)%20000;
shared_buffer[i] = product;
count++;
if (!(count % 5000))
printf("produit: %d %d\n", j, product);
sleep(0.05);
}
return NULL;
}
void* consommateur(void* args) {
int j, product = 0;
int count = 0;
while (1) {
int i = -1;
while (++i < N) {
if (shared_buffer[i] != -1) {
break;
}
}
if (i >= N) {
sleep(0.05);
continue;
}
product = (shared_buffer[i]+product)%20000;
j = (i+j)%20000;
shared_buffer[i] = -1;
count++;
if (!(count %5000))
printf("résultat: %d %d %d\n", j, product);
sleep(0.05);
}
return NULL;
}
int main() {
for (int i=0; i < N; i++) {
shared_buffer[i] = -1;
}
pthread_t tid[PROD+CONS];
for (int i=0; i < PROD; i++) {
pthread_create(&(tid[i]), NULL, &producteur, NULL);
}
for (int i=0; i < CONS; i++) {
pthread_create(&(tid[i+PROD]), NULL, &consommateur, NULL);
}
for (int i=0; i < PROD+CONS; i++) {
pthread_join(tid[i], NULL);
}
return 0;
}