int main(int argc, char **argv) { int fd = 0, stat, nconflicts; long i, j, nproc; sem_t *ptr; pid_t pid; ssize_t n; if (argc != 2) err_quit("usage: locksvsemrace1 <#processes>"); nproc = atol(argv[1]); Pipe(pipefd); ptr = My_shm(sizeof(sem_t)); /* create memory-based semaphore */ Sem_init(ptr, 1, 0); for (j = 0; j < nproc; j++) { if (Fork() == 0) { /* 4child */ Sem_wait(ptr); /* wait for parent to start children */ for (i = 0; i < 10; i++) { my_lock(fd); /* lock the file */ my_unlock(fd); /* unlock the file */ } exit(0); } /* parent loops around, creating next child */ } for (j = 0; j < nproc; j++) Sem_post(ptr); /* start all the children */ /* now just wait for all the children to finish */ while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) ; Close(pipefd[1]); nconflicts = 0; while ( (n = Read(pipefd[0], &stat, 1)) > 0) nconflicts += n; printf("%d conflicts\n", nconflicts); exit(0); }
int main(int argc, char **argv) { int i, nprocs; pid_t childpid[MAXNPROC]; if (argc != 3) err_quit("usage: incr_rwlock5 <#loops> <#processes>"); nloop = atoi(argv[1]); nprocs = min(atoi(argv[2]), MAXNPROC); /* 4get shared memory for parent and children */ shared = My_shm(sizeof(struct shared)); /* 4initialize the read-write lock and obtain write lock */ Rwlock_init(&shared->rwlock, USYNC_PROCESS, NULL); Rw_wrlock(&shared->rwlock); /* 4create all the children */ for (i = 0; i < nprocs; i++) { if ( (childpid[i] = Fork()) == 0) { incr(NULL); exit(0); } } /* 4parent: start the timer and release the write lock */ Start_time(); Rw_unlock(&shared->rwlock); /* 4wait for all the children */ for (i = 0; i < nprocs; i++) { Waitpid(childpid[i], NULL, 0); } printf("microseconds: %.0f usec\n", Stop_time()); if (shared->counter != nloop * nprocs) printf("error: counter = %ld\n", shared->counter); exit(0); }
int main(int argc, char **argv) { int i, nprocs; pid_t childpid[MAXNPROC]; if (argc != 3) err_quit("usage: incr_pxsem9 <#loops> <#processes>"); nloop = atoi(argv[1]); nprocs = min(atoi(argv[2]), MAXNPROC); /* 4get shared memory for parent and children */ shared = My_shm(sizeof(struct shared)); /* 4initialize memory-based semaphore to 0 */ Sem_init(&mutex, 1, 0); /* 4create all the children */ for (i = 0; i < nprocs; i++) { if ( (childpid[i] = Fork()) == 0) { incr(NULL); exit(0); } } /* 4parent: start the timer and release the semaphore */ Start_time(); Sem_post(&mutex); /* 4wait for all the children */ for (i = 0; i < nprocs; i++) { Waitpid(childpid[i], NULL, 0); } printf("microseconds: %.0f usec\n", Stop_time()); if (shared->counter != nloop * nprocs) printf("error: counter = %ld\n", shared->counter); exit(0); }