// threadtest.cc (revised) // John H. Hine // Simple producer/consumer example for lab exercise 1. //---------------------------------------------------------------------- #include "copyright.h" #include "system.h" #include "synchlist.h" //---------------------------------------------------------------------- // Producer/Consumer // List q is global and shared between producer and consumer // threads. // Threads // Loop 5 times, inserting/removing an item into/from the list // and yielding the CPU to another ready thread each iteration. //---------------------------------------------------------------------- SynchList *q; void Producer(int which) { int num; for (num = 0; num < 5; num++) { int *n = new int; *n = num; q->Append(n); printf("*** Producer appended %d to list\n", *n); currentThread->Yield(); } } void Consumer(int which) { int num; int *n; for (num = 0; num < 5; num++) { n=(int *)q->Remove(); printf("*** Consumer removed %d from list\n", *n); currentThread->Yield(); } } //---------------------------------------------------------------------- // ThreadTest // Set up a ping-pong between two threads, by forking a thread // to call Consumer, and then calling Producer using this main thread. //---------------------------------------------------------------------- void ThreadTest() { DEBUG('t', "Entering Producer/Consumer\n"); q = new SynchList(); Thread *t = new Thread("Consumer"); t->Fork(Consumer,0); Producer(1); }