zoukankan      html  css  js  c++  java
  • 多线程用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
    ", 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
    ", 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
    ", i);
                return 2;
            }
        }
        SetEvent(hEvents[0]);
        
        WaitForMultipleObjects(N_OBJECTS, hThreads, true, INFINITE);
    
        printf("
    
    Bye!
    ");
        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!

     
  • 相关阅读:
    phpspider爬虫框架的使用
    【php设计模式】责任链模式
    【php设计模式】策略模式
    【php设计模式】观察者模式
    【php设计模式】模板模式
    【温故知新】php 魔术方法
    【php设计模式】享元模式
    Java50道经典习题-程序18 乒乓球赛
    Java50道经典习题-程序19 输入行数打印菱形图案
    Java50道经典习题-程序20 求前20项之和
  • 原文地址:https://www.cnblogs.com/endenvor/p/13437904.html
Copyright © 2011-2022 走看看