/* ---------------------------------------------------------------- */ /* pingpong.c: */ /* This program forces an alternating execution of two threads. */ /* ---------------------------------------------------------------- */ #include #include #include "mtuThread.h" void Ping(int); /* thread prototypes */ void Pong(int); SEM_t StopPing, StopPong; int Count; /* ---------------------------------------------------------------- */ /* Ping(): */ /* Function Ping() */ /* ---------------------------------------------------------------- */ void Ping(int ID) { while (1) { /* loop forever */ SEMAPHORE_WAIT(StopPing); /* stop until released */ printf("Ping-"); /* print Ping- */ SEMAPHORE_SIGNAL(StopPong); /* release Pong */ } THREAD_EXIT(); } /* ---------------------------------------------------------------- */ /* Pong(): */ /* Function Pong() */ /* ---------------------------------------------------------------- */ void Pong(int ID) { do { /* loop for 'Count' times */ SEMAPHORE_WAIT(StopPong); /* stop until released */ printf("Pong\n"); /* append Pong to Ping- */ SEMAPHORE_SIGNAL(StopPing); /* release Ping */ Count--; } while (Count > 0); /* done if Count = 0 */ THREAD_EXIT(); } /* ---------------------------------------------------------------- */ /* The main program */ /* ---------------------------------------------------------------- */ int main(int argc, char *argv[]) { THREAD_t THREAD_Ping, THREAD_Pong; Count = 10; if (argc != 2) { printf("Use %s #-of-iterations\n", argv[0]); printf("No. of iterations is set to %d\n", Count); } else Count = abs(atoi(argv[1])); StopPing = SEMAPHORE_INIT(1); /* Ping goes first */ StopPong = SEMAPHORE_INIT(0); /* Pong stops until informed*/ THREAD_Ping = THREAD_CREATE(Ping, THREAD_SIZE, THREAD_NORMAL, 1, (char **) 0); THREAD_Pong = THREAD_CREATE(Pong, THREAD_SIZE, THREAD_NORMAL, 2, (char **) 0); THREAD_JOIN(THREAD_Pong); /* can only join Pong() */ return 0; }