2011-03-10, 11:24 AM
(This post was last modified: 2011-03-10, 02:41 PM by Unauthorized Intruder.)
Producer should be finished before Consumer starts. I have no idea where should I place WaitForSingleObject for both mutex and semaphore. I placed like this and most of the time Consumer starts and finished before Producer even starts.
It's either Producer starts first, result is as it should be. Or Consumer starts first, and wrong result.
This is a school project. I have to use either Mutex or Semaphore or both.
Edit: Never mind. Problem solved. Just change from Semaphore to same mutex.
It's either Producer starts first, result is as it should be. Or Consumer starts first, and wrong result.
This is a school project. I have to use either Mutex or Semaphore or both.
Edit: Never mind. Problem solved. Just change from Semaphore to same mutex.
Code:
DWORD Sum;
int ct = 0;
buffer_item buffer[BUFFER_SIZE];
HANDLE Mutex;
HANDLE Sem;
bool finished = false;
int insert_item(int item)
{
buffer[ct] = item;
printf("Producer is producing %d into slot %d.\n", item, ct);
ct = ct++;
if (ct > BUFFER_SIZE)
ct = ct-(BUFFER_SIZE);
return 0;
}
int remove_item()
{
printf("Consuming %d in slot %d\n", (int) buffer[ct], ct);
buffer[ct] = NULL;
ct--;
return 0;
}
DWORD WINAPI Producer(LPVOID item)
{
WaitForSingleObject(Mutex, INFINITE);
printf("Producer created. Now waiting for the thread to finish.\n");
int ob;
for (int i = 1; i<= 5;i++)
{
ob = rand();
insert_item(ob);
}
finished = true;
printf("Producer finished.\n");
ReleaseMutex(Mutex);
return 0;
}
DWORD WINAPI Consumer(LPVOID item)
{
//while (!finished); <- I put this to see how it should work.
WaitForSingleObject(Sem, INFINITE);
printf("Consumer created. Now waiting for the thread to finish.\n");
while(ct> 0)
remove_item();
printf("Consumer finished.\n");
ReleaseSemaphore(Sem, 1, NULL);
return 0;
}
int main(int argc,char *argv[])
{
Mutex = CreateMutex(NULL, FALSE, NULL);
DWORD ThreadID;
HANDLE ThreadHandle;
int unused;
ThreadHandle = CreateThread(NULL,0,Producer,&unused,0,&ThreadID);
DWORD ThreadID2;
HANDLE ThreadHandle2;
Sem = CreateSemaphore(NULL, 1, 5, NULL);
ThreadHandle2 = CreateThread(NULL, 0, Consumer, &unused, 0, &ThreadID2);
Sleep(1000);
return 0;
}
