首先来一个可用的 程序,WaitForMultipleObjects会等现成结束后,才会继续走下去。【本例子从msdn官网改造 http://msdn.microsoft.com/en-us/library/ms686927(v=vs.85).aspx 】
#include <windows.h> #include <stdio.h> #define THREADCOUNT 4 DWORD WINAPI WriteToDatabase( LPVOID ); int main( void ) { HANDLE aThread[THREADCOUNT]; int i; // Create worker threads for( i=0; i < THREADCOUNT; i++ ) { DWORD ThreadID; aThread[i] = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE) WriteToDatabase, NULL, // no thread function arguments 0, // default creation flags &ThreadID); // receive thread identifier if( aThread[i] == NULL ) { printf("CreateThread error: %d\n", GetLastError()); return 1; } } // Wait for all threads to terminate printf("~~WaitForMultipleObjects Start...\n"); WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE); printf("~~WaitForMultipleObjects End...\n"); // Close thread and mutex handles for( i=0; i < THREADCOUNT; i++ ) CloseHandle(aThread[i]); return 0; } DWORD WINAPI WriteToDatabase( LPVOID lpParam ) { // lpParam not used in this example UNREFERENCED_PARAMETER(lpParam); // Request ownership of mutex. printf("Thread %d writing to database...\n",GetCurrentThreadId()); Sleep(1500); return TRUE; }
把 THREADCOUNT 线程数 修改为100,再运行,立刻结束,很郁闷。
把 THREADCOUNT 线程数 修改为50,再运行,正常等待线程结束。
我不知道究竟是哪里的问题。。。
线程一多就失效了,暂时用: http://msdn.microsoft.com/en-us/library/ms687055(v=vs.85).aspx Waiting for Multiple Objects (Windows) 建立一个Event 来等待。或许Event一多也不行,反正 这个 我很困惑。