I have three source file called supermercato.c
cliente.c
cassiere.c
and the following header file cliente.h
cassiere.h
. supermercato.c
is where is main()
. In supermercato()
there I create two thread which are located in the other two source files but I have a shared structure and I don't know how to share all of these. Please can someone help me ?
'''
#include "librerie.h"
#include "cliente.h"
#define K 5 //numero totale di casse del supermercato
#define C 20 //numero totale clienti
#define UNIX_PATH_MAX 108
#define SOCKNAME "./mysock"
#define ec_meno1(s,m) \
if((s) == -1) { perror(m); exit(EXIT_FAILURE); }
#define ec_null(s,m) \
if((s) == NULL) { perror(m); exit(EXIT_FAILURE); }
#define ec_zero(s,m) \
if((s) != 0) { perror(m); exit(EXIT_FAILURE); }
//these two
int casse_aperte = 0;
casse c[K];
int main(int argc,char* argv[]){
//lettura file parametri
pthread_t tid_cassiere[K];
pthread_t tid_cliente[C];
//inizializza casse
for(int i=0;i<K;i++){
c[i].num_clienti=0;
c[i].q=NULL;
ec_zero((pthread_mutex_init(&c[i].mtx,NULL)),"pthread_mutex_init failed");
ec_zero((pthread_cond_init(&c[i].empty,NULL)),"pthread_cond_init failed");
ec_zero((pthread_cond_init(&c[i].full,NULL)),"pthread_cond_init failed");
}
//apro una cassa
ec_zero((pthread_create(&tid_cassiere[0],NULL,cassiere,&c[0])),"pthread_create failed");
casse_aperte++;
//genero un cliente
for(int i=0;i<C;i++){
//generare numero random [0,K-1] rand
ec_zero((pthread_create(&tid_cliente[i],NULL,cliente,&c[0])),"pthread_create failed");
}
for(int i=0;i<C;i++){
ec_zero((pthread_join(tid_cliente[i],NULL)),"join failed");
}
ec_zero((pthread_join(tid_cassiere[0],NULL)),"join failed");
return 0;
}
The following is cliente.h
/**
Thread cliente
*/
//se K non e' stata definita ==> la definisco
#ifndef K
#define K 5
#endif
typedef struct coda{
int val;
struct coda *next;
}coda;
typedef struct cassa{
int num_clienti;
coda *q;
pthread_mutex_t mtx;
pthread_cond_t empty;
pthread_cond_t full;
}casse;
extern int casse_aperte;
extern casse c[K];
void* cliente(void *c);
the following is cliente.c
#include "librerie.h"
#include "cliente.h"
//funzione thread cliente
void* cliente(void *c){
//all'atto dell'entrata genero numero casuale [0,P]
printf("CLIENTE\n");
if(c == NULL){
perror("invalid argument");
exit(EXIT_FAILURE);
}
casse* cassa = (casse*)c;
pthread_mutex_lock(&cassa->mtx);
while(cassa->num_clienti != 0){ //in questo caso condizione mai verificata perche c'e'
solo un cliente
//il cliente valuta se cambiare coda (ogni volta che si sveglia dopo la signal)
pthread_cond_wait(&cassa->empty,&cassa->mtx);
}
cassa->num_clienti++;
printf("cliente si accoda e produce un valore\n");
pthread_cond_signal(&cassa->full);
pthread_mutex_unlock(&cassa->mtx);
return NULL;
}
And librerie.h
is where there are all the standard libraries included