读书人

WaitForMultipleObjects 究竟什么意思

发布时间: 2013-01-18 10:22:42 作者: rapoo

WaitForMultipleObjects 到底什么意思, 什么作用? 请看代码


#include <iostream>
#include <windows.h>
using namespace std;

#define MAX_SEM_COUNT 10
#define THREADCOUNT 12

HANDLE ghSemaphore;

DWORD WINAPI ThreadProc( LPVOID );

void main()
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;

// Create a semaphore with initial and max counts of MAX_SEM_COUNT

ghSemaphore = CreateSemaphore(
NULL, // default security attributes
MAX_SEM_COUNT, // initial count
MAX_SEM_COUNT, // maximum count
NULL); // unnamed semaphore

if (ghSemaphore == NULL)
{
printf("CreateSemaphore error: %d\n", GetLastError());
return;
}

// Create worker threads

for( i=0; i < THREADCOUNT; i++ )
{
aThread[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) ThreadProc,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier

if( aThread[i] == NULL )
{
printf("CreateThread error: %d\n", GetLastError());
return;
}
}

// Wait for all threads to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE); // 这个函数到底是什么作用? 什么叫做等待内核对象?

// Close thread and semaphore handles



for( i=0; i < THREADCOUNT; i++ )
CloseHandle(aThread[i]);

CloseHandle(ghSemaphore);
}

DWORD WINAPI ThreadProc( LPVOID lpParam )
{
BOOL bContinue=TRUE;

while(bContinue)
{}
return TRUE;
}



[解决办法]
WaitForMultipleObjects简单点说就是等待第二个参数中的内核对象的,当内核对象有信号时,调用线程才会被调度,并返回值,顺序执行下去。

windows程序中有内核对象 用户对象 和GDI对象。 要理解他,好好看看《windows核心编程》

读书人网 >C++

热点推荐