zoukankan      html  css  js  c++  java
  • 《Windows核心编程》第十一章——线程池

    • 隐式使用工作项
    #include <iostream>
    #include <windows.h>
    
    int g_nCount = 0;
    VOID NTAPI SimpleCallback(PTP_CALLBACK_INSTANCE pInstance, PVOID pvContext)
    {
        g_nCount++;
        printf("test:%d
    ", g_nCount);
    }
    
    void main()
    {
        int nCount = 500;
        PTP_SIMPLE_CALLBACK pFunc = SimpleCallback;
        while (0 != nCount)
        {
            TrySubmitThreadpoolCallback(pFunc, NULL, NULL);
    
            nCount--;
        }
        getchar();
    }

    通过结果观察发现,利用了线程池,输出并非有序:

    显式地控制工作项

    void main()
    {
        g_pWorkItem = CreateThreadpoolWork(TaskHandler, NULL, NULL);
        if (NULL == g_pWorkItem)
        {
            return;
        }
        int nCount = 5000;
        while (nCount)
        {
            SubmitThreadpoolWork(g_pWorkItem);
            nCount--;
        }
        WaitForThreadpoolWorkCallbacks(g_pWorkItem, FALSE);
        CloseThreadpoolWork(g_pWorkItem);
        getchar();
    }

    如果改为下面这样,则会报错:

    int g_nCount = 0;
    PTP_WORK g_pWorkItem = NULL;
    
    void NTAPI TaskHandler(PTP_CALLBACK_INSTANCE Instance, PVOID Context, PTP_WORK work)
    {
        g_nCount++;
        printf("test:%d..
    ", g_nCount);
    }
    
    unsigned int _stdcall testthread(PVOID pParam)
    {
        int nCount = 500;
        while (nCount)
        {
            SubmitThreadpoolWork(g_pWorkItem);
            nCount--;
        }
    
        return 0;
    }
    
    void main()
    {
        g_pWorkItem = CreateThreadpoolWork(TaskHandler, NULL, NULL);
        if (NULL == g_pWorkItem)
        {
            return;
        }
      _beginthreadex(NULL, 0, testthread, NULL, 0, NULL);
    WaitForThreadpoolWorkCallbacks(g_pWorkItem, FALSE); CloseThreadpoolWork(g_pWorkItem); getchar(); }

    因为据书上说,只能取消或等待本线程中的工作项。

  • 相关阅读:
    mysql多表查询
    mysql单表查询
    第四篇: 记录相关操作
    第4章-1.生成3的乘方表 (15分)
    第3章-17.输出10个不重复的英文字母 (50分)
    第3章-22.判断两个字符串是否为变位词 (40分)
    第3章-21.输出大写英文字母 (15分)
    第3章-20.判断回文字符串 (15分)
    第3章-19.逆序的三位数 (10分)
    第3章-18.找最长的字符串 (15分)
  • 原文地址:https://www.cnblogs.com/predator-wang/p/9098487.html
Copyright © 2011-2022 走看看