2013-07-07 50 views
0

我正在嘗試處理類中的線程池。下面是 是我的代碼。試圖處理一個類中的線程池

#include <Windows.h> 

class ClassA 
{ 
public : // user API 
    ClassA() 
    { 
    } 

    ~ClassA() 
    { 
    } 

public : //my muiti-thread func 

    void init() 
    { 
     //************************************* 
     // multithread Initialization 
     //************************************* 
     pool = NULL; 
     cleanupgroup = NULL; 
     rollback = 0; 
     bool bRet = false; 

     pool = CreateThreadpool(NULL); 
     if(NULL == pool) 
     { 
      goto cleanPool; 
     } 
     rollback = 1;          

     SetThreadpoolThreadMaximum(pool, 5);     
     bRet = SetThreadpoolThreadMinimum(pool, 10); 

     if (FALSE == bRet) { 
      goto cleanPool; 
     } 

     cleanupgroup = CreateThreadpoolCleanupGroup(); 

     if (NULL == cleanupgroup) { 
      goto cleanPool; 
     } 

     rollback = 2;          

     SetThreadpoolCallbackPool(&CallBackEnviron, pool); 

     SetThreadpoolCallbackCleanupGroup(&CallBackEnviron, 
      cleanupgroup, 
      NULL); 

     return ; 

cleanPool: 
     switch (rollback) 
     { 
     case 2: 
      // Clean up the cleanup group. 
      CloseThreadpoolCleanupGroup(cleanupgroup); 

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

     default: 
      break; 
     } 

     return ; 
    } 

    void foo() 
    { 
     PTP_WORK work = NULL; 
     work = CreateThreadpoolWork(ClassA::_delegate, 
         NULL, 
         &CallBackEnviron); 
    } 

    static void __stdcall _delegate(PTP_CALLBACK_INSTANCE Instance, PVOID Parameter, PTP_WORK Work) 
    { 
     //some code 
    } 

    PTP_POOL pool; 
    UINT rollback; 
    TP_CALLBACK_ENVIRON CallBackEnviron;  
    PTP_CLEANUP_GROUP cleanupgroup; 
}; 

int main() 
{ 
    ClassA a; 
    a.init(); 
    a.foo(); 
} 

如果你做一個項目,並執行該代碼,它得到未處理execption ...... 我不知道爲什麼......

+0

這並不回答你的問題,但你可能會發現Boost.Thread庫更易於使用和更便攜。 – crowder

+0

@crowder確實能在課堂上處理泳池嗎? –

+0

這個網站上有很多線程池的例子。 – crowder

回答

1

我覺得異常是由未初始化的結構CallBackEnviron引起的。 documentation指出此結構必須初始化InitializeThreadpoolEnvironment

+0

在init()之前添加InitializeThreadpoolEnvironment(&CallBackEnviron),就在SetThreadpoolCallbackPool使異常消失之前。 – manuell

+0

我很尷尬,因爲我的錯誤... Thx manuell :) –