int main(int argc, char **argv) { int i, nthreads, count[MAXNTHREADS]; pthread_t tid_produce[MAXNTHREADS], tid_consume; if (argc != 3) err_quit("Usage: prodcons2 <#items> <#threads>"); nitems = min(atoi(argv[1]), MAXNITEMS); nthreads = min(atoi(argv[2]), MAXNTHREADS); Pthread_setconcurrency(nthreads); // start all the producer threads for (i = 0; i < nthreads; i++) { count[i] = 0; Pthread_create(&tid_produce[i], NULL, produce, &count[i]); } //wait for all the producer threads for (i = 0; i < nthreads; i++) { Pthread_join(tid_produce[i], NULL); printf("count[%d] = %d\n", i, count[i]); } //start then wait for the consumer thread Pthread_create(&tid_consume, NULL, consume, NULL); Pthread_join(tid_consume, NULL); exit(0); }
int main(int argc, char **argv) { pthread_t tid_produce, tid_consume; if (argc != 2) err_quit("Usage: pc <#items>"); nitems = atoi(argv[1]); //create three semaphore shared.mutex = Sem_open(Px_ipc_name(SEM_MUTEX), O_CREAT | O_EXCL, FILE_MODE, 1); shared.nempty = Sem_open(Px_ipc_name(SEM_NEMPTY), O_CREAT | O_EXCL, FILE_MODE, NBUFF); shared.nstored = Sem_open(Px_ipc_name(SEM_NSTORED), O_CREAT | O_EXCL, FILE_MODE, 0); //create one producer thread and one consumer thread Pthread_setconcurrency(2); Pthread_create(&tid_produce, NULL, produce, NULL); Pthread_create(&tid_consume, NULL, consume, NULL); //wait for the two threads Pthread_join(tid_produce, NULL); Pthread_join(tid_consume, NULL); //remove the semaphores Sem_unlink(Px_ipc_name(SEM_MUTEX)); Sem_unlink(Px_ipc_name(SEM_NEMPTY)); Sem_unlink(Px_ipc_name(SEM_NSTORED)); exit(0); }
int main(int argc, char **argv) { pthread_t tid_produce, tid_consume; if (argc != 2) err_quit("Usage: buffer <pathname>"); fd = Open(argv[1], O_RDONLY); Sem_init(&shared.mutex, 0, 1); Sem_init(&shared.nempty, 0, NBUFF); Sem_init(&shared.nstored, 0, 0); Pthread_setconcurrency(2); Pthread_create(&tid_produce, NULL, produce, NULL); Pthread_create(&tid_consume, NULL, consume, NULL); Pthread_join(tid_produce, NULL); Pthread_join(tid_consume, NULL); Sem_destroy(&shared.mutex); Sem_destroy(&shared.nempty); Sem_destroy(&shared.nstored); exit(0); }