Win32 API功能封装
+ -

CreateThreadpoolWork线程

2022-03-10 270 0
PTP_WORK WINAPI CreateThreadpoolWork(
  __in          PTP_WORK_CALLBACK pfnwk,
  __in_out_opt  PVOID pv,
  __in_opt      PTP_CALLBACK_ENVIRON pcbe
);

第一个参数是线程函数,第二个参数是给线程函数传的值(Context),第三个参数用作执行回调的环境。这个函数使用的函数模板是:

VOID CALLBACK WorkCallback(
  [in, out]            PTP_CALLBACK_INSTANCE Instance,
  [in, out, optional]  PVOID Context,
  [in, out]            PTP_WORK Work
);

创建工作项后,需要提交工作项给线程池,让线程池分配线程处理该项。提交工作项请求的函数是SubmitThreadpoolWork,定义如下:

VOID WINAPI SubmitThreadpoolWork(
  __in_out      PTP_WORK pwk
);

等待工作项完成的函数是WaitForThreadpoolWorkCallbacks,定义如下:

VOID WINAPI WaitForThreadpoolWorkCallbacks(
   __in_out      PTP_WORK pwk,
   __in          BOOL fCancelPendingCallbacks
 );

该函数的第二个参数
Indicates whether to cancel queued callbacks that have not yet started to execute.

取消工作项的函数是CloseThreadpoolWork,定义如下:

VOID WINAPI CloseThreadpoolWork(
  __in_out      PTP_WORK pwk
);

示例代码如下:

VOID CALLBACK WorkThread1(PTP_CALLBACK_INSTANCE Instance,PVOID Context,PTP_WORK Work)
{
    for (int i=0;i<5;i++)
    {
        AfxMessageBox(_T("this is a WorkCallback fun"));
        Sleep(1000);
    }
}

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
    ...
    PTP_WORK pw = CreateThreadpoolWork(WorkThread1,NULL,NULL);
    SubmitThreadpoolWork(pw);
    //给线程足够多的时间启动
    Sleep(2000);
    //TRUE,试图取消提交的工作项。如果工作项已启动,则等待;
    //FALSE,当前线程挂起,直到工作项完成
    WaitForThreadpoolWorkCallbacks(pw,TRUE);
    CloseThreadpoolWork(pw);
    ...
}

示例2:


static int
export_device(devno_t devno, SOCKET sockfd)
{
    PTP_WORK    work;
    forwarder_ctx_t    *pctx;

    pctx = (forwarder_ctx_t *)malloc(sizeof(forwarder_ctx_t));
    if (pctx == NULL) {
        dbg("out of memory");
        return ERR_GENERAL;
    }
    pctx->hdev = open_stub_dev(devno);
    if (pctx->hdev == INVALID_HANDLE_VALUE) {
        dbg("cannot open devno: %hhu", devno);
        return ERR_NOTEXIST;
    }
    pctx->sockfd = sockfd;

    work = CreateThreadpoolWork(forwarder_stub, pctx, NULL);
    if (work == NULL) {
        dbg("failed to create thread pool work: error: %lx", GetLastError());
        CloseHandle(pctx->hdev);
        free(pctx);
        return ERR_GENERAL;
    }
    SubmitThreadpoolWork(work);
    return 0;
}


static VOID CALLBACK
forwarder_stub(PTP_CALLBACK_INSTANCE inst, PVOID ctx, PTP_WORK work)
{
    forwarder_ctx_t    *pctx = (forwarder_ctx_t *)ctx;

    dbg("stub forwarding started");

    usbip_forward((HANDLE)pctx->sockfd, pctx->hdev, TRUE);

    closesocket(pctx->sockfd);
    CloseHandle(pctx->hdev);
    free(pctx);

    CloseThreadpoolWork(work);

    dbg("stub forwarding stopped");
}

0 篇笔记 写笔记

CreateThreadpoolWork线程
PTP_WORK WINAPI CreateThreadpoolWork( __in PTP_WORK_CALLBACK pfnwk, __in_out_opt PVOID pv, __in_opt PTP_CALLBACK_ENVIRON pcbe);......
作者信息
我爱内核
Windows驱动开发,网站开发
好好学习,天天向上。
取消
感谢您的支持,我会继续努力的!
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

您的支持,是我们前进的动力!