简体   繁体   中英

How to use Win32 ThreadPool API?

This version (based on this article) works:

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

VOID
CALLBACK
MyWorkCallback(
    PTP_CALLBACK_INSTANCE Instance,
    PVOID                 Parameter,
    PTP_WORK              Work
)
{
    // Instance, Parameter, and Work not used in this example.
    UNREFERENCED_PARAMETER(Instance);
    UNREFERENCED_PARAMETER(Parameter);
    UNREFERENCED_PARAMETER(Work);

    DWORD threadId = GetCurrentThreadId();

    BOOL bRet = FALSE;

    //
    // Do something when the work callback is invoked.
    //
    {
        _tprintf(_T("MyWorkCallback: ThreadId = %d Task performed.\n"), threadId);
    }

    return;
}

int main()
{
    TP_CALLBACK_ENVIRON CallBackEnviron;
    PTP_POOL pool = NULL;
    PTP_CLEANUP_GROUP cleanupgroup = NULL;
    PTP_WORK_CALLBACK workcallback = MyWorkCallback;
    PTP_TIMER timer = NULL;
    PTP_WORK work = NULL;


    InitializeThreadpoolEnvironment(&CallBackEnviron);
    pool = CreateThreadpool(NULL);
    SetThreadpoolThreadMaximum(pool, 1);
    SetThreadpoolThreadMinimum(pool, 3);
    cleanupgroup = CreateThreadpoolCleanupGroup();
    SetThreadpoolCallbackPool(&CallBackEnviron, pool);
    SetThreadpoolCallbackCleanupGroup(&CallBackEnviron, cleanupgroup, NULL);
    work = CreateThreadpoolWork(workcallback, NULL, &CallBackEnviron);
    for (int i = 0; i < 10; ++i)
    {
        SubmitThreadpoolWork(work);
    }
}

However, this version also works (with the same work function from above):

int main()
{
    PTP_WORK = CreateThreadpoolWork(workcallback, NULLPTR, NULLPTR);
    for (int i = 0; i < 10; ++i)
    { 
        SubmitThreadpoolWork(work);
    }
}

What are the differences between the two versions (except for the minimum and maximum thread count)?
Why would I use one version over another?

This is covered in the documentation for InitializeThreadpoolEnvironment :

Create a callback environment if you plan to call one of the following functions to modify the environment:

  • SetThreadpoolCallbackCleanupGroup

  • SetThreadpoolCallbackLibrary

  • SetThreadpoolCallbackPool

  • SetThreadpoolCallbackPriority

  • SetThreadpoolCallbackRunsLong

If you need the functionality provided by one or more of the listed functions, then you need to create a callback environment. If you don't, you don't.

If in doubt when starting a new project, use the simple approach to begin with, and see whether it meets your needs. You can always go back and switch to the more complex variant if and when it becomes necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM