Exemplo n.º 1
0
void thrdRequest(LPVOID lpvThreadParam) {
	long i;
	bool waiting = true;
	CString outbuffer;
	char tempclock[100];

	while (!exitFlag) {
		Sleep(4000);
		LogEvent("Current Process Requesting Access to Critical Section");
		WaitForSingleObject(sRequest, INFINITE);
		WaitForSingleObject(sReply, INFINITE);
		WaitForSingleObject(sClock, INFINITE);
		insertRequest(gProcessID, myclock);

		for (i=1; i<= NUMBEROFPROCESSES; i++) {
			if (i != gProcessID) {
				ReplyQueue[i-1] = false;
				outbuffer = "REQUEST:";
				outbuffer += ltoa(gProcessID,tempclock, 10);
				outbuffer += ":";
				outbuffer += ltoa(myclock, tempclock, 10);
				sendMessage(outbuffer, i);
			}
		}
		waitingForReply = true;
		myclock++;
		ReleaseSemaphore(sClock, 1, &i);
		ReleaseSemaphore(sReply, 1, &i);
		ReleaseSemaphore(sRequest, 1, &i);
		while (waiting) {
			waiting = false;
			WaitForSingleObject(sReply, INFINITE);
			WaitForSingleObject(sAlive, INFINITE);
			for (i=0; i<NUMBEROFPROCESSES; i++) {
				if ((i+1) != gProcessID) {
					if (AliveQueue[i]) {
						if (ReplyQueue[i] == false) waiting = true;
					}
				}
			}
			ReleaseSemaphore(sAlive, 1, &i);
			ReleaseSemaphore(sReply, 1, &i);
		}
		waiting = true;
		WaitForSingleObject(sClock, INFINITE);
		criticalsection();
		ReleaseSemaphore(sClock, 1, &i);
		WaitForSingleObject(sRequest, INFINITE);
		RequestQueue[gProcessID -1] = -1;
		ReleaseSemaphore(sRequest, 1, &i);
	}
	ExitThread(0);
}//end of Request thread
//FUNCTION TO DEMONSTRATE MUTEX USE
void runmutex()
{
	rq *temp=NULL;
  int np,i;
	printf("\n Enter number of processes in ready queue\n");
	scanf("%d",&np);
	while(np--)
	    headofrq=createrq(&headofrq);
	temp=removeprocess(&headofrq);
	while(temp)
	  {
	  	if(mutex)
	  	{
	  	   criticalsection(temp);
	  	   temp=removeprocess(&headofrq);
	    }
	  }
	printf("\n\n All Processes have finished their critical sections successfully\n\n");	
}