文档章节

Windows线程池Demo

rise-worlds
 rise-worlds
发布于 2016/06/20 13:42
字数 794
阅读 1
收藏 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

没有更多内容

加载失败,请刷新页面

加载更多

阿里P8架构师谈:如何打造一份高并发编程知识体系

1.问题 1、什么是线程的交互方式? 2、如何区分线程的同步/异步,阻塞/非阻塞? 3、什么是线程安全,如何做到线程安全? 4、如何区分并发模型? 5、何谓响应式编程? 6、操作系统如何调度多线...

小刀爱编程
9分钟前
0
0
比特币:如何用地址查询交易?

在比特币应用开发中,一个常见的问题就是,在知道比特币地址的情况下,如何查询这个地址上发生的所有交易?或者类似的说法,如何查询一个指定的比特币地址发生的所有交易? 本文将给出这一问...

汇智网教程
11分钟前
1
0
Spring Boot 下,敏感词及特殊字符过滤处理方式

背景: 技术采用的是 Spring Boot ,请求方法主要为 POST, 请求使用较多的注解为 @RequestBody 交付测试人员进行测试,测试人员在对模糊搜索模块进行了各种特殊字符的搜索,以至于敏感词和特...

Ryan-瑞恩
16分钟前
0
0
使用 Jenkins X 渐进式交付

本文首发于:Jenkins 中文社区 这是渐进式交付系列的第二篇文章,第一篇请看:Kubernetes 中的渐进式交付:蓝绿部署和金丝雀部署。 我使用的我的 Croc Hunter 示例项目评估了 Jenkins X 中金...

Jenkins中文社区
23分钟前
1
0
零基础学算法->PI

本文章是介绍几种计算PI的方法 1.概率法计算PI(又称蒙特卡罗法) 1.1 定义,过程 在半径为1的圆1/4的区域,通过随机函数产生横纵坐标值x,y;当x*x+y*y<=1时,满足条件。 1.2 结果: 因为是随机...

tedzheng
26分钟前
0
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部