#include <iostream.h>
#include <windows.h>
#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 0x00000080
// 采用这个宏可以限制线程池的最大线程数
#define WT_SET_MAX_THREADPOOL_THREADS(Flags,Limit) \
((Flags)|=(Limit)<<16)
DWORD WINAPI ThreadProc(LPVOID lpThreadParameter)
{
cout << "test " << hex << ::GetCurrentThreadId() << endl;
while(true)
{
Sleep(1000);
cout << "test " << hex << ::GetCurrentThreadId() << endl;
}
// ExitThread( 0 );
return 0; // 这里 return 0; 线程并没有真正结束
}
DWORD WINAPI ThreadProc1(LPVOID lpThreadParameter)
{
while(true)
{
Sleep(1000);
cout << "test1 " << hex << ::GetCurrentThreadId() << endl;
}
return 0;
}
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;
}