I'm writing a basic producer/consumer threading code. I got most of it to work, but I'm having an issue with rand(). Or maybe my issues are deeper than rand(), and rand is only the tip of the iceberg. I don't want to do anything too complex, (none of the runnable or wait).
I have a global deque of integers that acts as the buffer. I allow the user to enter in the size and the limit of run times. I make the counter a static global variable. this is my producer:
DWORD WINAPI producer(LPVOID n)
{
cout << "\nPRODUCER:The producer is running right now" << endl;
int size = (int)n;
int num = rand()%10;// this is for making item.
while (buffer.size() > size)
{
}
buffer.push_back(num);
counter++;
return (DWORD)n;
}
this is my consumer--
DWORD WINAPI consumer(LPVOID n)
{
cout << "\nCONSUMER:The consumer is running right now" << endl;
while (buffer.empty())
{ }
int item= buffer.front();
cout << "\nCONSUMER:The consumer ate" << item << endl;
counter++;
return (DWORD)n;
}
in main-
while (counter < l)
{
hThreads[0] = CreateThread(NULL, 0, producer, (LPVOID)s, NULL, &id[0]);
hThreads[1] = CreateThread(NULL, 0, consumer, (LPVOID)l, NULL, &id[1]);
waiter = WaitForMultipleObjects(MAX_THREADS, hThreads, TRUE, INFINITE);
}
for (int i = 0; i < MAX_THREADS; i++) {
CloseHandle(hThreads[i]);
}
So it only generates 1 every time. Srand didn't work either. But it runs the correct number of times.
EDIT--- So I fixed producer and consumer to deal with the race condition:
DWORD WINAPI producer(LPVOID s)
{
WaitForSingleObject(Empty, INFINITE);
WaitForSingleObject(Mutex, INFINITE);
cout << "\nPRODUCER...." << endl;
int size = (int)s;
srand(size);
int in = rand() % 10;
cout << "THIS IS IN:::" << in << endl;
while (buffer.size() == size)
{
ReleaseMutex(Mutex);
}
buffer.push_back(in);
counter++;
cout << "\nThe producer produces " << buffer.front() << endl;
ReleaseMutex(Mutex);
ReleaseSemaphore(Full, 1, NULL);
return (DWORD)s;
}
DWORD WINAPI consumer(LPVOID l)
{
WaitForSingleObject(Full, INFINITE);
WaitForSingleObject(Mutex, INFINITE);
cout << "\nCONSUMER...." << endl;
while (buffer.empty())
{
ReleaseMutex(Mutex);
}
int out = buffer.front();
counter++;
ReleaseMutex(Mutex);
ReleaseSemaphore(Empty, 1, NULL);
return (DWORD)l;
}
BUT the random thing still keeps acting up. It only keeps producing one number over and over (even when seeded).