Hello,
I'm trying my hand at coming up with an event-driven multithreading framework, based upon the idea of each thread waiting on a variable number of event handles. When any given event is signaled, the thread examines a queue associated with the event, does something related to what it finds there, then goes back to waiting.
Code:
while ((dwRet = WaitForMultipleObjects(nCount, hEvents, FALSE, INFINITE)) != WAIT_FAILED)
{
// do stuff
}
Now for the quirk: when waiting for any event to be signaled (not all of them, otherwise the FALSE in the above statement would be TRUE), each event is evaluated in order. So as it stands, if the first event in the hEvents array was particularly noisy, the thread would never see signals from the other events.
The way to get around this is to change the order of the events each time one is signaled, so that the signaled one is pushed to the end of the array. This would give other events a chance.
So with this in mind, I devised the following function, to be called at the end of the loop:-
Code:
void ReorderWaitHandles(DWORD nCount, LPHANDLE lpHandles, DWORD nSignaledIndex, void **ppAssociated)
{
HANDLE hTemp;
void *pTemp;
if (nSignaledIndex < nCount - 1)
{
hTemp = lpHandles[nSignaledIndex];
memcpy(&lpHandles[nSignaledIndex], &lpHandles[nSignaledIndex + 1], ((nCount - 1) - nSignaledIndex) * sizeof(*lpHandles));
lpHandles[nCount - 1] = hTemp;
if (ppAssociated)
{
pTemp = ppAssociated[nSignaledIndex];
memcpy(&ppAssociated[nSignaledIndex], &ppAssociated[nSignaledIndex + 1], ((nCount - 1) - nSignaledIndex) * sizeof(*ppAssociated));
ppAssociated[nCount - 1] = pTemp;
}
}
}
The function takes an array lpHandles, of nCount size, pushes lpHandles[nSignaledIndex] to the end of the array and optionally does the same for an identically-ordered pointer-sized array (the queues, in this case).
However, I seem to find that when I put this into practice, with an array of four event handles:-
[Event 1]
[Event 2]
[Event 3]
[Event 4]
If I opt to remove e.g. Event 2 from the array, with the following code:-
Code:
hEvents[1] = NULL;
nCount--;
After ReorderWaitHandles is called, WaitForMultipleObjects fails. It does this because of the presence of a NULL handle in the hEvents array. But I can't seem to work out how to resolve this. I know it's something simple, but my mind is clouded. Help please?