在windows上,系统提供了QueueUserWorkItem函数来实现异步调用。 此函数相当于在线程池中生成多个用户工作项目,与常规线程机制一样,线程池也有同步线程等机制。
【函数原型】
oolwinapiqueueuserworkitem (_ in lpthread _ start _ routine function,__in PVOID Context,__in ULONG Flags ); 【参数分析】
函数是用户定义的函数
上下文是PVOID指针,也是函数的参数;
Flags表示一系列标志值,作用可以通过调查MSDN来看到
WT_EXECUTEDEFAULT :将工作项放在非I/O组件线程中。
WT_EXECUTEINIOTHREAD :工作项位于I/O组件的线程中。 这些线程在I/O请求完成之前不会停止运行,并防止因线程终止而导致的I/O请求丢失。
WT_EXECUTEINPERSISTENTTHREAD :放入永久线程池。
WT_EXECUTELONGFUNCTION :工作项需要长时间工作,系统将相应地调度更多线程。
【示例代码】
# include assert.h # include windows.h # include iostream # includestringusingnamespacestd; dwordwinapithread1(pvoidpcontext ); dwordwinapithread2(pvoidpcontext ); dwordwinapithread3(pvoidpcontext ); CRITICAL_SECTION g_cs; intmain(intargc,char * argv[] ) handlehcompleteevent=create event (null,FALSE,FALSE,null ); initializecriticalsection(g_cs; queueuserworkitem(thread1,L'I'm thread 1',WT_EXECUTEINLONGTHREAD ); queueuserworkitem(thread2,L'I'm thread 2',WT_EXECUTEINLONGTHREAD ); queueuserworkitem(thread3,L'I'm thread 3',WT_EXECUTEINLONGTHREAD ); witforsingleobject (完成,信息); deletecriticalsection(g_cs; closehandle (完成事件; //getchar (; 返回0; //dwordwinapithread1(pvoidpcontext ) entercriticalsection (g _ cs ); wchar_t*wszval=(wchar_t* ) pContext; wcout L'wszVal:' wszVal endl; leavecriticalsection(g_cs; for(intI=0; i=50; I )企业级安全(g _ cs ); cout ' onethreadoutput : ' iendl; leavecriticalsection(g_cs; }返回0; //dwordwinapithread2(pvoidpcontext ) entercriticalsection(g_cs ); wchar_t*wszval=(wchar_t* ) pContext; wcout L'wszVal:' wszVal endl; leavecriticalsection(g_cs; for(intI=0; i=50; I )企业级安全(g _ cs ); cout ' twothreadoutput : ' iendl; leavecriticalsection(g_cs; }返回0; //dwordwinapithread3(pvoidpcontext ) entercriticalsection(g_cs ); wchar_t*wszval=(wchar_t* ) pContext; wcout L'wszVal:' wszVal endl; leavecriticalsection(g_cs; for(intI=0; i=50; I )企业级安全(g _ cs ); cout ' threethreadoutput : ' iendl; leavecriticalsection(g_cs; }返回0; }