1. 程式人生 > 實用技巧 >多執行緒用Event控制流程

多執行緒用Event控制流程

#define N_OBJECTS 26

HANDLE hEvents[N_OBJECTS];
HANDLE hThreads[N_OBJECTS];

DWORD WINAPI PrintChar(LPVOID lpParam)
{
    int i = (int)lpParam;
    printf("current thread id = %d, ready\n", i);
    Sleep(rand() % 100);
    WaitForSingleObject(hEvents[i], -1);
    printf("%c, ", i+'A');
    Sleep(rand() 
% 300); SetEvent(hEvents[i+1]); return 0; } int main() { srand(time(nullptr)); for (int i = 0; i < N_OBJECTS; i++) { hEvents[i] = CreateEvent(nullptr, false, false, nullptr); if (!hEvents[i]) { printf("CreateEvent %d falied\n", i);
return 1; } } for (int i = 0; i < N_OBJECTS; i++) { hThreads[i] = CreateThread(nullptr, 0, PrintChar, (LPVOID)i, 0, nullptr); if (!hThreads[i]) { printf("CreateThread %d falied\n", i); return 2; } } SetEvent(hEvents[
0]); WaitForMultipleObjects(N_OBJECTS, hThreads, true, INFINITE); printf("\n\nBye!\n"); return 0; }

Output:

current thread id = 0, ready
current thread id = 1, ready
current thread id = 2, ready
current thread id = 3, ready
current thread id = 4, ready
current thread id = 5, ready
current thread id = 6, ready
current thread id = 7, ready
current thread id = 8, ready
current thread id = 9, ready
current thread id = 10, ready
current thread id = 11, ready
current thread id = 12, ready
current thread id = 13, ready
current thread id = 14, ready
current thread id = 15, ready
current thread id = 16, ready
current thread id = 17, ready
current thread id = 19, ready
current thread id = 18, ready
current thread id = 20, ready
current thread id = 21, ready
current thread id = 22, ready
current thread id = 23, ready
current thread id = 24, ready
current thread id = 25, ready
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z,


Bye!