多線程代碼windows

#include <iostream.h>
#include <windows.h>ios

#define WT_EXECUTEDEFAULT 0x00000000
#define WT_EXECUTEINIOTHREAD 0x00000001
#define WT_EXECUTEINWAITTHREAD 0x00000004
#define WT_EXECUTEONLYONCE 0x00000008
#define WT_EXECUTELONGFUNCTION 0x00000010
#define WT_EXECUTEINTIMERTHREAD 0x00000020
#define WT_EXECUTEINPERSISTENTTHREAD 0x00000080windows

// 採用這個宏能夠限制線程池的最大線程數
#define WT_SET_MAX_THREADPOOL_THREADS(Flags,Limit) \
    ((Flags)|=(Limit)<<16)spa


DWORD WINAPI ThreadProc(LPVOID lpThreadParameter)
{
 cout << "test " << hex << ::GetCurrentThreadId() << endl;線程

 
 while(true)
 {
  Sleep(1000);
  cout << "test " << hex << ::GetCurrentThreadId() << endl;
 }orm

// ExitThread( 0 );it

 return 0; // 這裏 return 0; 線程並無真正結束
}io

DWORD WINAPI ThreadProc1(LPVOID lpThreadParameter)
{
 while(true)
 {
  Sleep(1000);
  cout << "test1 " << hex << ::GetCurrentThreadId() << endl;
 }test

 return 0;
}stream

BOOL WINAPI QueueUserWorkItem(LPTHREAD_START_ROUTINE Function, PVOID Context, ULONG Flags)
{
    typedef BOOL (WINAPI *LPQueueUserWorkItem)(LPTHREAD_START_ROUTINE Function, PVOID Context, ULONG Flags);
    LPQueueUserWorkItem pfnQueueUserWorkItem = NULL;   
    pfnQueueUserWorkItem = (LPQueueUserWorkItem)::GetProcAddress(::LoadLibrary("kernel32.dll"), "QueueUserWorkItem");
    
 if ( NULL == pfnQueueUserWorkItem )
 {
  return FALSE;
 }
 else
 {
  return pfnQueueUserWorkItem(Function, Context, Flags);   
 }
}線程池


int main(int argc,char **argv)

 DWORD dt = WT_EXECUTEONLYONCE;

 // 若是在 ThreadProc 裏面調用 ExitThread( 0 );, 則不會開啓 Thread1 線程
 // 但 QueueUserWorkItem 竟然返回值是 TRUE
 //BOOL b = QueueUserWorkItem(ThreadProc, (void*)1 , WT_SET_MAX_THREADPOOL_THREADS(dt, 1));   
    
 // WT_EXECUTEINIOTHREAD 參數
    dt = WT_EXECUTEDEFAULT;
 BOOL b = QueueUserWorkItem(ThreadProc, (void*)1 , WT_SET_MAX_THREADPOOL_THREADS(dt, 4));   
    
 if( !b )
  cout << "Failed to Create Thread" << endl;

 Sleep(5000);

 // 若是在 ThreadProc 裏面沒有調用 ExitThread( 0 );, 在 Thread 和 Thread1 中看到的線程ID是一致的
 dt = WT_EXECUTEONLYONCE;
 
 //b = QueueUserWorkItem(ThreadProc1, (void*)1 , WT_SET_MAX_THREADPOOL_THREADS(dt, 1)); 

 // WT_EXECUTEINIOTHREAD 參數
 dt = WT_EXECUTEDEFAULT;
 b = QueueUserWorkItem(ThreadProc1, (void*)1 , WT_SET_MAX_THREADPOOL_THREADS(dt, 4)); 

 if( !b )
  cout << "Failed to Create Thread" << endl;

 Sleep(5000);

 // 程序退出時,即便 子線程沒有退出,系統也會強迫其退出?
 // WT_EXECUTEONLYONCE 與 WT_EXECUTEINIOTHREAD 的區別?   
 // 若是設置了 WT_EXECUTEINIOTHREAD 即不會執行到 Thread1?

 return 0;}

相關文章
相關標籤/搜索