Dijkstra
Enviado por Programa Chuletas y clasificado en Otras materias
Escrito el en español con un tamaño de 1,85 KB
#include
#include
#include
typedef struct{
int id; int *turno; int *b;
int *c; int n; }thilo;
void unlock(int id, int *b,
int *c, int *turno){ b[id] = 1;
c[id] = 1; *turno = 0;}
void lock(int id, int *b, int *c,
int *turno, int n){ int ok;
int otro; b[id] = 0;
do{ while(*turno!=id){
c[id]=1;
if (b[*turno])
*turno=id;}
c[id]=0; ok = 1;
for (otro=0; otro if (otro!=id)
ok = ok && c[otro];}
}while(!ok);}
void *codigo(void *p){
thilo *info_h; int i;
info_h = (thilo*)p;
lock(info_h->id, info_h->b, info_h->c, info_h->turno, info_h->n);
for (i = 0; i<10; i++){
printf("%d-%d ", info_h->id, i); usleep(10); }
printf("\\n");
unlock(info_h->id, info_h->b, info_h->c, info_h->turno);
return(NULL);}
int main(){int *turno;int *b, *c;
pthread_t *h; thilo *info_h;
int n, i; n = 7; turno=(int *)malloc(sizeof(int)); b =c= (int *)malloc(sizeof(int)*n);
h = (pthread_t *)malloc(sizeof(pthread_t)*n);
info_h = (thilo *)malloc(sizeof(thilo)*n);
*turno = 0; for (i = 0; i b[i]=c[i]=1;
}
for (i = 0; i info_h[i].id = i;
info_h[i].b = b;
info_h[i].c = c;
info_h[i].turno = turno;
info_h[i].n = n;
pthread_create(&(h[i]), NULL, codigo, &(info_h[i]));
}
for (i = 0; i pthread_join(h[i], NULL);
}
free(turno);
free(b);
free(c);
free(h);
free(info_h);
}
#include
#include
typedef struct{
int id; int *turno; int *b;
int *c; int n; }thilo;
void unlock(int id, int *b,
int *c, int *turno){ b[id] = 1;
c[id] = 1; *turno = 0;}
void lock(int id, int *b, int *c,
int *turno, int n){ int ok;
int otro; b[id] = 0;
do{ while(*turno!=id){
c[id]=1;
if (b[*turno])
*turno=id;}
c[id]=0; ok = 1;
for (otro=0; otro
ok = ok && c[otro];}
}while(!ok);}
void *codigo(void *p){
thilo *info_h; int i;
info_h = (thilo*)p;
lock(info_h->id, info_h->b, info_h->c, info_h->turno, info_h->n);
for (i = 0; i<10; i++){
printf("%d-%d ", info_h->id, i); usleep(10); }
printf("\\n");
unlock(info_h->id, info_h->b, info_h->c, info_h->turno);
return(NULL);}
int main(){int *turno;int *b, *c;
pthread_t *h; thilo *info_h;
int n, i; n = 7; turno=(int *)malloc(sizeof(int)); b =c= (int *)malloc(sizeof(int)*n);
h = (pthread_t *)malloc(sizeof(pthread_t)*n);
info_h = (thilo *)malloc(sizeof(thilo)*n);
*turno = 0; for (i = 0; i
}
for (i = 0; i
info_h[i].b = b;
info_h[i].c = c;
info_h[i].turno = turno;
info_h[i].n = n;
pthread_create(&(h[i]), NULL, codigo, &(info_h[i]));
}
for (i = 0; i
}
free(turno);
free(b);
free(c);
free(h);
free(info_h);
}