#include #include #include #include #include typedef struct { pthread_mutex_t *lock; int n; int running; } Info; void *waiter(void *arg) { Info *I; int status; I = (Info *) arg; while (1) { wait(&status); pthread_mutex_lock(I->lock); I->running--; if (I->running < I->n) { if (fork() == 0) { execlp("experiment", "experiment", NULL); exit(1); } I->running++; } pthread_mutex_unlock(I->lock); } } main() { Info I; pthread_t tid; int new_n, i; I.lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(I.lock, NULL); I.n = 0; I.running = 0; while (1) { if (scanf("%d", &new_n) != 1 || new_n <= 0) exit(0); pthread_mutex_lock(I.lock); while (I.running < new_n) { if (fork() == 0) { execlp("experiment", "experiment", NULL); exit(1); } I.running++; } if (I.n == 0) pthread_create(&tid, NULL, waiter, (void *) &I); I.n = new_n; pthread_mutex_unlock(I.lock); } }