文档章节

Windows线程池Demo

rise-worlds
 rise-worlds
发布于 2016/06/20 13:42
字数 794
阅读 3
收藏 0

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

//
// Thread pool wait callback function template
//
VOID
    CALLBACK
    MyWaitCallback(
    PTP_CALLBACK_INSTANCE Instance,
    PVOID                 Parameter,
    PTP_WAIT              Wait,
    TP_WAIT_RESULT        WaitResult
    )
{
    //
    // Do something when the wait is over.
    //
    _tprintf(_T("MyWaitCallback: wait is over.\n"));
}


//
// Thread pool timer callback function template
//
VOID
    CALLBACK
    MyTimerCallback(
    PTP_CALLBACK_INSTANCE Instance,
    PVOID                 Parameter,
    PTP_TIMER             Timer
    )
{
    //
    // Do something when the timer fires.
    //
    _tprintf(_T("MyTimerCallback: timer has fired.\n"));

}


//
// This is the thread pool work callback function.
// The callback demonstrates correct behavior when changing the
// state of the thread inside the callback function.
//
// Any changes to the thread state must be restored to original
// before exiting the callback routine.
//
VOID
    CALLBACK
    MyWorkCallback(
    PTP_CALLBACK_INSTANCE Instance,
    PVOID                 Parameter,
    PTP_WORK              Work
    )
{
    BOOL bRet = FALSE;
    DWORD dwPriorityOriginal = 0;

    //
    // Record the original thread priority.
    //
    dwPriorityOriginal = GetThreadPriority(GetCurrentThread());

    if (THREAD_PRIORITY_ERROR_RETURN == dwPriorityOriginal) {
        _tprintf(_T("GetThreadPriority failed.  LastError: %u\n"),
            GetLastError());
        return;
    }

    //
    // Increase the priority of the thread pool thread.
    //
    bRet = SetThreadPriority(GetCurrentThread(),
        THREAD_PRIORITY_ABOVE_NORMAL);

    if (FALSE == bRet) {
        _tprintf(_T("SetThreadPriority failed.  LastError: %u\n"),
            GetLastError());
        return;
    }

    _tprintf(_T("MyWorkCallback: thread priority increased.\n"));


    //
    // Perform tasks at increased priority.
    //
    {
        _tprintf(_T("MyWorkCallback: task performed at increased priority.\n"));

    }

    //
    // Restore thread state by resetting the original priority.
    //
    bRet = SetThreadPriority(GetCurrentThread(),
        dwPriorityOriginal);

    //
    // If restore fails, maybe retry or throw an exception.  Otherwise,
    // the thread will continue to execute other work items at increased
    // priority.
    //
    if (FALSE == bRet) {
        _tprintf(_T("Fatal Error! SetThreadPriority failed. LastError: %u\n"),
            GetLastError());
        return;
    }

    _tprintf(_T("MyWorkCallback: thread priority restored.\n"));

    return;
}

VOID
    DemoCleanupPersistentWorkTimer()
{
    BOOL bRet = FALSE;
    PTP_WORK work = NULL;
    PTP_TIMER timer = NULL;
    PTP_POOL pool = NULL;
    PTP_WORK_CALLBACK workcallback = MyWorkCallback;
    PTP_TIMER_CALLBACK timercallback = MyTimerCallback;
    TP_CALLBACK_ENVIRON CallBackEnviron;
    PTP_CLEANUP_GROUP cleanupgroup = NULL;
    FILETIME FileDueTime;
    ULARGE_INTEGER ulDueTime;
    UINT rollback = 0;

    InitializeThreadpoolEnvironment(&CallBackEnviron);

    //
    // Create a custom, dedicated thread pool.
    //
    pool = CreateThreadpool(NULL);

    if (NULL == pool) {
        _tprintf(_T("CreateThreadpool failed. LastError: %u\n"),
            GetLastError());
        goto main_cleanup;
    }

    rollback = 1; // pool creation succeeded

    //
    // The thread pool is made persistent simply by setting
    // both the minimum and maximum threads to 1.
    //
    SetThreadpoolThreadMaximum(pool, 1);

    bRet = SetThreadpoolThreadMinimum(pool, 1);

    if (FALSE == bRet) {
        _tprintf(_T("SetThreadpoolThreadMinimum failed. LastError: %u\n"),
            GetLastError());
        goto main_cleanup;
    }

    //
    // Create a cleanup group for this thread pool.
    //
    cleanupgroup = CreateThreadpoolCleanupGroup();

    if (NULL == cleanupgroup) {
        _tprintf(_T("CreateThreadpoolCleanupGroup failed. LastError: %u\n"),
            GetLastError());
        goto main_cleanup;
    }

    rollback = 2;  // Cleanup group creation succeeded

    //
    // Associate the callback environment with our thread pool.
    //
    SetThreadpoolCallbackPool(&CallBackEnviron, pool);

    //
    // Associate the cleanup group with our thread pool.
    // Objects created with the same callback environment
    // as the cleanup group become members of the cleanup group.
    //
    SetThreadpoolCallbackCleanupGroup(&CallBackEnviron,
        cleanupgroup,
        NULL);

    //
    // Create work with the callback environment.
    //
    work = CreateThreadpoolWork(workcallback,
        NULL,
        &CallBackEnviron);

    if (NULL == work) {
        _tprintf(_T("CreateThreadpoolWork failed. LastError: %u\n"),
            GetLastError());
        goto main_cleanup;
    }

    rollback = 3;  // Creation of work succeeded

    //
    // Submit the work to the pool. Because this was a pre-allocated
    // work item (using CreateThreadpoolWork), it is guaranteed to execute.
    //
    SubmitThreadpoolWork(work);


    //
    // Create a timer with the same callback environment.
    //
    timer = CreateThreadpoolTimer(timercallback,
        NULL,
        &CallBackEnviron);


    if (NULL == timer) {
        _tprintf(_T("CreateThreadpoolTimer failed. LastError: %u\n"),
            GetLastError());
        goto main_cleanup;
    }

    rollback = 4;  // Timer creation succeeded

    //
    // Set the timer to fire in one second.
    //
    ulDueTime.QuadPart = (LONGLONG) -(1 * 10 * 1000 * 1000);
    FileDueTime.dwHighDateTime = ulDueTime.HighPart;
    FileDueTime.dwLowDateTime  = ulDueTime.LowPart;

    SetThreadpoolTimer(timer,
        &FileDueTime,
        0,
        0);

    //
    // Delay for the timer to be fired
    //
    Sleep(1500);

    //
    // Wait for all callbacks to finish.
    // CloseThreadpoolCleanupGroupMembers also releases objects
    // that are members of the cleanup group, so it is not necessary
    // to call close functions on individual objects
    // after calling CloseThreadpoolCleanupGroupMembers.
    //
    CloseThreadpoolCleanupGroupMembers(cleanupgroup,
        FALSE,
        NULL);

    //
    // Already cleaned up the work item with the
    // CloseThreadpoolCleanupGroupMembers, so set rollback to 2.
    //
    rollback = 2;
    goto main_cleanup;

main_cleanup:
    //
    // Clean up any individual pieces manually
    // Notice the fall-through structure of the switch.
    // Clean up in reverse order.
    //

    switch (rollback) {
    case 4:
    case 3:
        // Clean up the cleanup group members.
        CloseThreadpoolCleanupGroupMembers(cleanupgroup,
            FALSE, NULL);
    case 2:
        // Clean up the cleanup group.
        CloseThreadpoolCleanupGroup(cleanupgroup);

    case 1:
        // Clean up the pool.
        CloseThreadpool(pool);

    default:
        break;
    }

    return;
}

VOID
    DemoNewRegisterWait()
{
    PTP_WAIT Wait = NULL;
    PTP_WAIT_CALLBACK waitcallback = MyWaitCallback;
    HANDLE hEvent = NULL;
    UINT i = 0;
    UINT rollback = 0;

    //
    // Create an auto-reset event.
    //
    hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    if (NULL == hEvent) {
        // Error Handling
        return;
    }

    rollback = 1; // CreateEvent succeeded

    Wait = CreateThreadpoolWait(waitcallback,
        NULL,
        NULL);

    if(NULL == Wait) {
        _tprintf(_T("CreateThreadpoolWait failed. LastError: %u\n"),
            GetLastError());
        goto new_wait_cleanup;
    }

    rollback = 2; // CreateThreadpoolWait succeeded

    //
    // Need to re-register the event with the wait object
    // each time before signaling the event to trigger the wait callback.
    //
    for (i = 0; i < 5; i ++) {
        SetThreadpoolWait(Wait,
            hEvent,
            NULL);

        SetEvent(hEvent);

        //
        // Delay for the waiter thread to act if necessary.
        //
        Sleep(500);

        //
        // Block here until the callback function is done executing.
        //

        WaitForThreadpoolWaitCallbacks(Wait, FALSE);
    }

new_wait_cleanup:
    switch (rollback) {
    case 2:
        // Unregister the wait by setting the event to NULL.
        SetThreadpoolWait(Wait, NULL, NULL);

        // Close the wait.
        CloseThreadpoolWait(Wait);

    case 1:
        // Close the event.
        CloseHandle(hEvent);

    default:
        break;
    }
    return;
}

int _tmain(int argc, _TCHAR* argv[])
{
    DemoNewRegisterWait();
    DemoCleanupPersistentWorkTimer();
    return 0;
}

本文转载自:http://www.cnblogs.com/flying_bat/archive/2010/07/05/1771771.html

rise-worlds

rise-worlds

粉丝 2
博文 1755
码字总数 0
作品 0
深圳
程序员
私信 提问
piggy_xrh/libstpool

.简介 libstpool是一个开源的轻便的跨平台的动态c/c++线程池,任务池库, 支持Windows, Linux, Unix, ARM, MAC/OSX, NDK,提供丰富的特性支持. .特性 (支持) (支持) (支持) 静态线程池 (支持...

piggy_xrh
2015/01/23
0
0
支持缓存线程池的ThreadLocal--Transmittable ThreadLocal(TTL)

主页 功能 需求场景 User Guide 2.1 修饰Runnable和Callable 2.2 修饰线程池 2.3 使用Java Agent来修饰JDK线程池实现类 整个过程的完整时序图 Java Agent的使用方式在什么情况下TTL会失效 ...

oldratlee
2013/12/05
3.2K
0
java常用的几种线程池实例讲解

很多时候我们在使用某些东西,但是自己并不知道在使用或者压根就不关注;就像人呼吸空气却从来不关注这个,我使用线程池也是如此。在无意中用了却并不知道我使用了,(当然我现在也没发现,就...

相公
2017/12/20
0
0
Java消息队列任务的平滑关闭

1.问题背景 对于消息队列任务的监听,我们一般使用Java写一个独立的程序,在Linux服务器上运行。当订阅者程序启动后,会通过消息队列客户端接收消息,放入线程池中并发的处理。 那么问题来了...

蛙牛
2016/11/14
4.4K
20
Binder,Binder线程池,AIDL demo - Android

-- Binder线程池,Android Binder 连接池; AIDL demo Binder线程池的主要作用就是将每个业务模块的Binder请求统一转发到远程Servie中去执行,从而避免了重复创建Service的过程。 https://gi...

desaco
2018/10/25
0
0

没有更多内容

加载失败,请刷新页面

加载更多

tomcat 莫名奔溃问题

Apr 24, 2019 6:18:11 PM org.apache.coyote.AbstractProtocol pause INFO: Pausing ProtocolHandler ["http-nio-8080"] Apr 24, 2019 6:18:12 PM org.apache.coyote.AbstractProtocol pause......

mellen
14分钟前
0
0
组件开发规范 class名身份识别

组件需要通过一个组件共有的class来标识这个组件,外部调用的时候,可以通过锁定这个class来方便地改变组件的css样式。 设置方式 .my-checkbox { width: 20px; height: 20px; font-...

Carbenson
22分钟前
0
0
如何在工作中快速成长?致工程师的10个简单技巧

阿里妹导读:阿里有句非常经典的土话,“今天的最好表现,是明天的最低要求。”如何挖掘潜能、发现更好的自己?今天,阿里巴巴高级无线开发专家江建明将认知升级的方法总结出来,帮助你获得快...

阿里云云栖社区
42分钟前
2
0
PHP和Redis实现在高并发下的抢购及秒杀功能

抢购、秒杀是平常很常见的场景,面试的时候面试官也经常会问到,比如问你淘宝中的抢购秒杀是怎么实现的等等。 抢购、秒杀实现很简单,但是有些问题需要解决,主要针对两个问题: 一、高并发对...

xiaogg
43分钟前
1
0
从数据上看:谁才是漫威的绝对C位

复联4上映了!这次比美国还早了两天。当然,我还没看,不会给你们剧透,当然也不想不剧透。 这一部不仅是灭霸这一线剧情的结局,也被认为漫威第三阶段的收官之作。据说此部之后,不少影迷熟知...

crossin
57分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部