I'm trying to implement a real-world simulation involving synchronization, and when I have an event that has an 80% chance of occurring, I'm currently doing
while((rand()%10)<8){
up(sCar);
printf("SOUTH: new car\n");
}
However, the while loop is never triggering while ran, so I'm not sure if I'm using rand() properly. If I replace the rand() with 7, when it works properly. I currently set
srand (time(NULL));
earlier in my program as well. Any help would be much appreciated.
EDIT: Here is the full running program. I have modified sys.c to create the system calls for up and down, which act as Semaphores.
#include <linux/unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <time.h>
struct cs1550_sem{
int value;
struct listnode *start;
struct listnode *finish;
};
void up(struct cs1550_sem *sem) {
syscall(__NR_cs1550_up, sem);
}
void down(struct cs1550_sem *sem) {
syscall(__NR_cs1550_down, sem);
}
int main(void){
srand (time(NULL));
void * ptr = mmap(NULL, sizeof(struct cs1550_sem)*3, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
struct cs1550_sem *nCar = ((struct cs1550_sem *)ptr);
struct cs1550_sem *sCar = ((struct cs1550_sem *)ptr) + 1;
struct cs1550_sem *mutex = ((struct cs1550_sem *)ptr) + 2;
struct cs1550_sem *flag = ((struct cs1550_sem *)ptr) + 3;
void * northRoad = mmap(NULL, sizeof(int)*(10+1), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
void * southRoad = mmap(NULL, sizeof(int)*(10+1), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, 0, 0);
nCar->value = 0;
nCar->start= NULL;
nCar->finish = NULL;
sCar->value = 0;
sCar->start= NULL;
sCar->finish = NULL;
flag->value = 0;
flag->start= NULL;
flag->finish = NULL;
mutex->value = 1;
mutex->start= NULL;
mutex->finish = NULL;
if(fork()==0){
while(1){
while((rand()%10)<8){
up(nCar);
printf("NORTH: new car\n");
}
printf("NORTH: no more cars, sleeping for 20 seconds\n");
sleep(20);
}
}
else if(fork()==0){
while(1){
while((rand()%10)<8){
up(sCar);
printf("SOUTH: new car\n");
}
printf("SOUTH: no more cars, sleeping for 20 seconds\n");
sleep(20);
}
}
else if(fork()==0){
while(1){
down(nCar);
down(mutex);
printf("NORTH car allowed through\n");
up(mutex);
}
}
else{
while(1){
down(sCar);
down(mutex);
printf("SOUTH car allowed through\n");
up(mutex);
}
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire