#include /* This is q3.c */ #include #include struct ts { pthread_mutex_t *lock; pthread_cond_t *cv1, *cv2; char *command; int id; }; void *thread(void *arg) { struct ts *T; int i; T = (struct ts *) arg; // usleep(1000); pthread_mutex_lock(T->lock); for (i = 0; T->command[i] != '\0'; i++) { if (T->command[i] == 'S') { pthread_mutex_unlock(T->lock); sleep(1); pthread_mutex_lock(T->lock); } if (T->command[i] == 'X') pthread_cond_wait(T->cv1, T->lock); if (T->command[i] == 'Y') pthread_cond_wait(T->cv2, T->lock); if (T->command[i] == 'A') pthread_cond_signal(T->cv1); if (T->command[i] == 'B') pthread_cond_signal(T->cv2); if (T->command[i] == 'P') { printf("%c ", T->id); fflush(stdout); } if (T->command[i] == 'E') { printf("\n"); exit(1); } } pthread_mutex_unlock(T->lock); return NULL; } main(int argc, char **argv) { pthread_mutex_t lock; pthread_cond_t cv1, cv2; int i; pthread_t *tids; struct ts *T; void *dummy; pthread_mutex_init(&lock, NULL); pthread_cond_init(&cv1, NULL); pthread_cond_init(&cv2, NULL); T = (struct ts *) malloc(sizeof(struct ts)*(argc-1)); tids = (pthread_t *) malloc(sizeof(pthread_t)*(argc-1)); for (i = 0; i < argc-1; i++) { T[i].id = 'A' + i; T[i].lock = &lock; T[i].cv1 = &cv1; T[i].cv2 = &cv2; T[i].command = argv[i+1]; pthread_create(tids+i, NULL, thread, (void *) (T+i)); } for (i = 0; i < argc-1; i++) pthread_join(tids[i], &dummy); printf("\n"); }