Re: WaitForSingleObject
"Mihajlo Cvetanovi??" <mcvetanovic@gmail> ha scritto nel messaggio
news:eNHKJFNoKHA.5344@TK2MSFTNGP04.phx.gbl...
Actually "next time" has just come. When Consumer leaves its main loop it
erases the element from eventi map and then also from users map. But in
between the Producer may just find this element in its loop, feed some
data into users map, and call SetEvent with non-existing element! SetEvent
may or may not crash, I don't know and would dare not to test it in
working environment.
Ok! what about this?
while(1)
{
// CALLBACK EVENT
WaitForSingleObject(hevent, INFINITE);
EnterCriticalSection(&users_mutex);
int flag = users[threadid].cb.at(0).flag;
string line = (char*)users[threadid].cb.at(0).data;
ResetEvent(hevent);
LeaveCriticalSection(&users_mutex);
if(flag == BUFF_DONE)
{
int ret = s->SendBytes(line + CRLF);
if(SOCKET_ERROR == ret)
break;
}
}
// Close && Remove "event" and "users" from their maps
//
EnterCriticalSection(&users_mutex);
users.erase(threadid);
LeaveCriticalSection(&users_mutex);
EnterCriticalSection(&eventi_mutex);
eventi.erase(threadid);
LeaveCriticalSection(&eventi_mutex);
CloseHandle(hevent);
And one more problem connected with previous one, a race condition:
Producer may produce faster than Consumer can consume (even with
Sleep(1000) you are not really safe). The effect: some data is not sent,
because the Consumer sends only lastly produced data. The fix: in Consumer
erase all consumed data, and consume from the end instead from beginning,
and don't ResetEvent if there are more data to consume.
Well, since I am using pushing back in the circula buffer what I push is the
newest data and so forth. On the Consumer I need to get oldest data...or
maybe I ma getting that wrong...