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(); }

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

  • 相关阅读:
    3-12 初识JWT
    3-11 用户登录信息验证实现
    3-10 公共模块统一测试
    3-9 公共业务异常统一处理
    3-8 公共返回对象封装
    3-7 公共请求对象封装及优雅验证数据实现
    3-6 MD5介绍及用户添加功能实现
    3-5 用户模块数据层构建
    3-4 用户模块构建
    3-3 公共工具模块构建
  • 原文地址:https://www.cnblogs.com/predator-wang/p/9098487.html
Copyright © 2011-2022 走看看