最初由 doskey 发布 Sample Multithread C Program Home | Overview | How Do I | Sample
BOUNCE.C is a sample multithread program that creates a new thread each time the letter a or A is typed. Each thread bounces a “happy face” of a different color around the screen. Up to 32 threads can be created. The program’s normal termination occurs when q or Q is typed. See Compiling and Linking Multithread Programs for details on compiling and linking BOUNCE.C.
/* Bounce - Creates a new thread each time the letter 'a' is typed. * Each thread bounces a happy face of a different color around the screen. * All threads are terminated when the letter 'Q' is entered. * * This program requires the multithread library. For example, compile * with the following command line: * CL /MT BOUNCE.C */
/* getrandom returns a random number between min and max, which must be in * integer range. */ #define getrandom( min, max ) ((rand() % (int)(((max) + 1) - (min))) + (min))
void main( void ); /* Thread 1: main */ void KbdFunc( void ); /* Keyboard input, thread dispatch */ void BounceProc( char * MyID ); /* Threads 2 to n: display */ void ClearScreen( void ); /* Screen clear */ void ShutDown( void ); /* Program shutdown */ void WriteTitle( int ThreadNum ); /* Display title bar information */
HANDLE hConsoleOut; /* Handle to the console */ HANDLE hRunMutex; /* "Keep Running" mutex */ HANDLE hScreenMutex; /* "Screen update" mutex */ int ThreadNr; /* Number of threads started */ CONSOLE_SCREEN_BUFFER_INFO csbiInfo; /* Console information */
void main() /* Thread One */ { /* Get display screen information & clear the screen.*/ hConsoleOut = GetStdHandle( STD_OUTPUT_HANDLE ); GetConsoleScreenBufferInfo( hConsoleOut, &csbiInfo ); ClearScreen(); WriteTitle( 0 ); /* Create the mutexes and reset thread count. */ hScreenMutex = CreateMutex( NULL, FALSE, NULL ); /* Cleared */ hRunMutex = CreateMutex( NULL, TRUE, NULL ); /* Set */ ThreadNr = 0;
/* Start waiting for keyboard input to dispatch threads or exit. */ KbdFunc();
/* All threads done. Clean up handles. */ CloseHandle( hScreenMutex ); CloseHandle( hRunMutex ); CloseHandle( hConsoleOut ); }
void ShutDown( void ) /* Shut down threads */ { while ( ThreadNr > 0 ) { /* Tell thread to die and record its death. */ ReleaseMutex( hRunMutex ); ThreadNr--; } /* Clean up display when done */ WaitForSingleObject( hScreenMutex, INFINITE ); ClearScreen(); }
void KbdFunc( void ) /* Dispatch and count threads. */ { int KeyInfo;