1#include <stdio.h>2#include <process.h>3#include <windows.h>4 5 //Number of Threads6 Const intThread_num =3;7 8 //Number of Cycles9 Const intLOOP =Ten;Ten One //Mutex Events AHANDLE G_hthreadevent[thread_num];//Child thread synchronization events -HANDLE G_semaphore;//the main thread synchronizes with the child thread - //volatile int g_count = 0; the intG_count =0; - -Unsignedint__stdcall Threadfunction (void*PPM) - { + intnum = * (int*) PPM; -ReleaseSemaphore (G_semaphore,1, NULL);//Signal Volume + + + A for(inti =0; i < LOOP; i++) at { - WaitForSingleObject (G_hthreadevent[num], INFINITE); - //InterlockedIncrement ((Lplong) &g_count); -g_count++; - -printf"page%d thread id:%3d, thread print:%c\n", G_count, GetCurrentThreadID (), num +'A'); in -SetEvent (g_hthreadevent[(num +1) %Thread_num]); to } + - return 0; the } * $ Panax Notoginseng intMainvoid) - { the inti =0; + HANDLE Hthreadhandle[thread_num]; AG_semaphore = CreateSemaphore (NULL,0,1, NULL);//currently 0 resources, maximum allowed 1 simultaneous visits the + for(i =0; i < Thread_num; i++) - { $G_hthreadevent[i] =CreateEvent (null, FALSE, FALSE, NULL); $ } - - for(i =0; i < Thread_num; i++) the { -Hthreadhandle[i] = (HANDLE) _beginthreadex (nullptr,0, Threadfunction, &i,0, nullptr);Wuyi WaitForSingleObject (G_semaphore, INFINITE); the } - WuSetEvent (g_hthreadevent[0]); - AboutWaitForMultipleObjects (Thread_num, Hthreadhandle,true, INFINITE); $ - for(i =0; i < Thread_num; i++) - { - CloseHandle (Hthreadhandle[i]); A CloseHandle (G_hthreadevent[i]); + } the - CloseHandle (g_semaphore); $ the return 0; the}
Open 3 threads, the IDs of these 3 threads are a, B, C, each thread will have its own ID on the screen, and the output must be displayed in the order of ABC: ABCABC