I need to solve Producer-Consumer problem in c++ using primitive synchronization objects - events, I already wrote this code
static int g_x = 0;
HANDLE hEvent1;
HANDLE aThread[2];
DWORD ThreadID;
//tread 1
void Producer()
{
for (int i = 0; i < 100; ++i)
{
WaitForSingleObject(hEvent1, INFINITE);
g_x = i;
SetEvent(hEvent1);
}
}
//thread 2
void Consumer()
{
for (;;)
{
WaitForSingleObject(hEvent1, INFINITE);
SetEvent(hEvent1);
}
}
int createthreads() {
hEvent1 = CreateEvent(NULL, FALSE, TRUE, NULL);
// Create worker threads
aThread[0] = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)Producer, NULL, 0, &ThreadID);
aThread[1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Consumer, NULL, 0, &ThreadID);
}
int main() {
createthreads();
}
This code doesn't work correctly: I have Infinite cycle
How can I fix this code to get in console numbers from 0
to 99
?