fuksa ha scritto:
c'è un altro modo per far avvenire tale comunicazione?
Copio e incollo con piccole modifiche da vecchio thread
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#define MAX 10
int A1[MAX];
int A2[MAX];
int A3[MAX];
sem_t W1, W2, W3;
void * writer_process1(void * arg){
int i = 0;
time_t start = time(0), s, t = 0;
while(i < MAX){
s = time(0) - start;
if(t != s){
t = s;
A1[i++] = i;
sem_post(&W1);
}
}
}
void * writer_process2(void * arg){
int i = 0;
time_t start = time(0), s, t = 0;
while(i < MAX){
s = time(0) - start;
if(t != s){
t = s;
A2[i++] = i;
sem_post(&W2);
}
}
}
void * writer_process3(void * arg){
int i = 0;
time_t start = time(0), s, t = 0;
while(i < MAX){
s = time(0) - start;
if(t != s){
t = s;
A3[i++] = i;
sem_post(&W3);
}
}
}
void * reader_process(void * arg){
for(int i = 0; i < MAX; i++){
sem_wait(&W1);
printf("Il processo 1 ha scritto A1[%d] = %d\n", i, A1[i]);
sem_wait(&W2);
printf("Il processo 2 ha scritto A2[%d] = %d\n", i, A2[i]);
sem_wait(&W3);
printf("Il processo 3 ha scritto A3[%d] = %d\n", i, A3[i]);
}
}
int main(){
pthread_t wr1, wr2, wr3, rd;
sem_init(&W1,0,0);
sem_init(&W2,0,0);
sem_init(&W3,0,0);
pthread_create(&wr1, NULL, writer_process1, NULL);
pthread_create(&wr2, NULL, writer_process2, NULL);
pthread_create(&wr3, NULL, writer_process3, NULL);
pthread_create(&rd, NULL, reader_process, NULL);
pthread_join(wr1, NULL);
pthread_join(wr2, NULL);
pthread_join(wr3, NULL);
pthread_join(rd, NULL);
return 0;
}