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!

     
  • 相关阅读:
    每日英语:Italian town fighting for its life over polluting Ilva steelworks
    SpringBoot + Kafka + ELK 完成海量日志收集(超详细)
    如何使用 Java 生成二维码?
    xyntservice
    windows service 与GUI窗口的实现
    一个可以查看HTML网页上密码框的程序(附源码)
    vss6 forgot admin password
    vs2005's addin folder
    javascript tips
    html中使用imagemap
  • 原文地址:https://www.cnblogs.com/endenvor/p/13437904.html
Copyright © 2011-2022 走看看