Pagini recente » Cod sursa (job #1450037) | Cod sursa (job #259059) | Cod sursa (job #622631) | Cod sursa (job #1670009) | Cod sursa (job #2955029)
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>
#include<time.h>
#include<unistd.h>
# define TIME_LIMIT 5
int doctor[50];
pthread_t thr[100];
pthread_mutex_t mtx[50];
struct pacient{
int id;
int doctor;};
void *repartizare(void* p){
struct pacient* p1=(struct pacient *) p;
time_t wait_s=time(NULL);
pthread_mutex_lock(&mtx[p1->doctor]);
int wait_f=time(NULL)-wait_s;
printf("Doctorul %d este ocupat.\n",p1->doctor);
time_t start=time(NULL);
sleep(rand()%TIME_LIMIT+1);
int durata=time(NULL)-start;
pthread_mutex_unlock(&mtx[p1->doctor]);
printf("Pacientul %d a asteptat %d minute la doctorul %d, iar consultatia a durat %d minute.\n",p1->id,wait_f,p1->doctor,durata);}
int main(int argc, char* argv[]){
int nr_p=atoi(argv[1]); //numar pacienti
int nr_d=atoi(argv[2]); //numar doctori
for(int i=0;i<nr_d;i++)
if ( pthread_mutex_init (& mtx[i] , NULL )) {
perror ( NULL );
return errno ;
}
int c=0;
srand(time(0));
for(int i=1;i<=nr_p;i++){
struct pacient * p= malloc(sizeof(p));
p->id=i;
p->doctor=rand()%nr_d;
if ( pthread_create (& thr[c++] , NULL , repartizare ,(void *)p)) {
perror ( NULL );
return errno ;
}
sleep(rand()%TIME_LIMIT);}
for(int i=1;i<=nr_p;i++)
if ( pthread_join ( thr[i] ,NULL )) {
perror ( NULL );
return errno ;}
}