Example #1
0
bool SjBusyInfo::Set__(const wxString& object, bool forceUpdateForLongOp)
{
	static bool inSet = FALSE;

	if( !inSet )
	{
		inSet = TRUE;

		unsigned long currMs = SjTools::GetMsTicks();
		if( !object.IsEmpty() )
		{
			m_objectCount++;
			wxLogDebug(wxT("m_objectCount=%i on SjBusyInfo::Set__(%s)"), (int)m_objectCount, object.c_str());

			if( forceUpdateForLongOp || currMs >= m_nextUpdateMs )
			{
				wxString label(object);
				if( label.StartsWith("file:") ) { label = wxFileSystem::URLToFileName(object).GetFullPath(); }

				m_objectNameWindow->SetLabel(label);
				m_objectCountWindow->SetLabel(SjTools::FormatNumber(m_objectCount));
				m_nextUpdateMs = currMs + UPDATE_INTERVALL_MS;
			}
		}

		unsigned long elapsedSeconds = (currMs-m_startTimeMs)/1000;
		if( elapsedSeconds != m_elapsedSeconds )
		{
			m_elapsedTimeWindow->SetLabel(SjTools::FormatTime(elapsedSeconds, SJ_FT_ALLOW_ZERO));
			m_elapsedSeconds = elapsedSeconds;
		}

		Yield();

		inSet = FALSE;
	}

	return !m_cancelPressed;
}
Example #2
0
int main() {
	int i, k; /* for loops */
	int appMoney = 0, picMoney = 0, passMoney = 0, cashMoney = 0;
	Setup();
	while(1) {
		for(k = 0; k < 60; k++) {
			ManagerCheckLines();
			for(i = 0; i < 70; i++) {
				Yield();
			}
		}
		ManagerCountMoney(&appMoney, &picMoney, &passMoney, &cashMoney);
		if(ManagerCheckClose() == true) {
			SetMV(doneFlag, 0, 1);
			for(i = 0; i < NUM_APPCLERKS; i++) {
				Acquire(appClerkMutex[i].clerkLock);
				Signal(appClerkMutex[i].clerkCV, appClerkMutex[i].clerkLock);
				Release(appClerkMutex[i].clerkLock);
			}
			for(i = 0; i < NUM_PICCLERKS; i++) {
				Acquire(picClerkMutex[i].clerkLock);
				Signal(picClerkMutex[i].clerkCV, picClerkMutex[i].clerkLock);
				Release(picClerkMutex[i].clerkLock);
			}
			for(i = 0; i < NUM_PASSCLERKS; i++) {
				Acquire(passClerkMutex[i].clerkLock);
				Signal(passClerkMutex[i].clerkCV, passClerkMutex[i].clerkLock);
				Release(passClerkMutex[i].clerkLock);
			}
			for(i = 0; i < NUM_CASHIERS; i++) {
				Acquire(cashierMutex[i].clerkLock);
				Signal(cashierMutex[i].clerkCV, cashierMutex[i].clerkLock);
				Release(cashierMutex[i].clerkLock);
			}
			break;
		}
	}
	Exit(0);
}
Example #3
0
File: mplpc.c Project: ACIIL/Quake
SOCKET
socket(int af, int type, int protocol)
{
   RTQ_NODE *n = MGenGetNode(IDLE_QUEUE);
   LPCData  *p;
   LPCReturn *r;
   SocketArgs  *args;
   int       retVal;

   _farsetsel(flat_selector);
   SocketError = 0;
   p = (LPCData *) FARPKL(&n->rtqDatum);
   SetLPCData(p);
   FARPOKL(&p->service, LPC_SOCKSOCKET);
   args = (SocketArgs *) p->Data;
   FARPOKL(&args->af, af);
   FARPOKL(&args->type, type);
   FARPOKL(&args->protocol, protocol);

   MGenMoveTo(IDLE_QUEUE, SEND_QUEUE);
   PostWindowsMessage();

   while ((n = MGenGetNode(REC_QUEUE)) == 0)
      Yield();

   r = (LPCReturn *) FARPKL(&n->rtqDatum);


   if (FARPKS(&r->error) != LPC_NOERROR) {
      return -1;
   }

   retVal = FARPKL(r->Data);

   // get ready for next call
   MGenMoveTo(REC_QUEUE, IDLE_QUEUE);

   return retVal;
}
Example #4
0
File: mplpc.c Project: ACIIL/Quake
int
getsockname(SOCKET s, struct sockaddr *name, int *namelen)
{
   RTQ_NODE *n = MGenGetNode(IDLE_QUEUE);
   LPCData  *p;
   LPCReturn *r;
   GetSockNameRet  *ret;
   int       retVal;

   SocketError = 0;
   _farsetsel(flat_selector);
   p = (LPCData *) FARPKL(&n->rtqDatum);
   SetLPCData(p);
   FARPOKL(&p->service, LPC_SOCKGETSOCKNAME);
   FARPOKL(p->Data, s);

   MGenMoveTo(IDLE_QUEUE, SEND_QUEUE);
   PostWindowsMessage();

   while ((n = MGenGetNode(REC_QUEUE)) == 0)
      Yield();


   r = (LPCReturn *) FARPKL(&n->rtqDatum);

   if (FARPKS(&r->error) != LPC_NOERROR) {
      return -1;
   }

   ret = (GetSockNameRet *) r->Data;
   retVal = FARPKL(&ret->retVal);
   fmemcpyfrom(name, ret->name, FARPKL(&ret->namelen));
   *namelen = FARPKL(&ret->namelen);

   // get ready for next call
   MGenMoveTo(REC_QUEUE, IDLE_QUEUE);

   return retVal;
}
Example #5
0
int
bind(SOCKET s, const struct sockaddr *name, int namelen)
{
   RTQ_NODE *n = MGenGetNode(IDLE_QUEUE);
   LPCData  *p;
   LPCReturn *r;
   BindArgs  *bargs;
   int       retVal;

   _farsetsel(flat_selector);
   SocketError = 0;
   p = (LPCData *) FARPKL(&n->rtqDatum);
   SetLPCData(p);
   FARPOKL(&p->service, LPC_SOCKBIND);
   bargs = (BindArgs *) p->Data;
   FARPOKL(&bargs->s, s);
   FARPOKL(&bargs->namelen, namelen);
   fmemcpyto(bargs->name, name, namelen);
   MGenMoveTo(IDLE_QUEUE, SEND_QUEUE);
   PostWindowsMessage();

   while ((n = MGenGetNode(REC_QUEUE)) == 0)
      Yield();

   r = (LPCReturn *) FARPKL(&n->rtqDatum);

   if (FARPKS(&r->error) != LPC_NOERROR) {
      return -1;
   }

   retVal = FARPKL(r->Data);

   // get ready for next call
   MGenMoveTo(REC_QUEUE, IDLE_QUEUE);

   return retVal;
}
Example #6
0
struct hostent *
gethostbyname(const char *name)
{
   RTQ_NODE *n = MGenGetNode(IDLE_QUEUE);
   LPCData  *p;
   LPCReturn *r;
   struct hostent *retVal;

   _farsetsel(flat_selector);
   SocketError = 0;
   p = (LPCData *) FARPKL(&n->rtqDatum);
   SetLPCData(p);
   FARPOKL(&p->service, LPC_SOCKGETHOSTBYNAME);
   fstrcpyto(p->Data, name);

   MGenMoveTo(IDLE_QUEUE, SEND_QUEUE);
   PostWindowsMessage();

   while ((n = MGenGetNode(REC_QUEUE)) == 0)
      Yield();

   r = (LPCReturn *) FARPKL(&n->rtqDatum);
   retVal = (struct hostent *) r->Data;

   if (FARPKL(&retVal->h_name) == 0) {
      retVal = 0;
   } else {
      ZapHostEnt();
      ReconstructHostEnt(&HostEnt, (void *) retVal);
      retVal = &HostEnt;
   }

   // get ready for next call
   MGenMoveTo(REC_QUEUE, IDLE_QUEUE);

   return retVal;
}
Example #7
0
int
WSAGetLastError(void)
{
   RTQ_NODE *n = MGenGetNode(IDLE_QUEUE);
   LPCData  *p;
   LPCReturn *r;
   int       retVal;


   _farsetsel(flat_selector);
   if (SocketError) {
      int err = SocketError;

      SocketError = 0;
      return err;
   }

   p = (LPCData *) FARPKL(&n->rtqDatum);
   SetLPCData(p);
   FARPOKL(&p->service, LPC_SOCKGETLASTERROR);

   MGenMoveTo(IDLE_QUEUE, SEND_QUEUE);
   PostWindowsMessage();

   while ((n = MGenGetNode(REC_QUEUE)) == 0)
      Yield();

   r = (LPCReturn *) FARPKL(&n->rtqDatum);


   retVal = FARPKL(r->Data);

   // get ready for next call
   MGenMoveTo(REC_QUEUE, IDLE_QUEUE);

   return retVal;
}
void ScreenshotCommand::CaptureToolbar(ToolManager *man, int type, wxString name)
{
   bool visible = man->IsVisible(type);
   if (!visible) {
      man->ShowHide(type);
      Yield();
   }

   wxWindow *w = man->GetToolBar(type);
   int x = 0, y = 0;
   int width, height;

   w->ClientToScreen(&x, &y);
   w->GetParent()->ScreenToClient(&x, &y);
   w->GetClientSize(&width, &height);

   Capture(name, w, x, y, width, height);

   if (!visible) {
      man->ShowHide(type);
      if (mIgnore)
         mIgnore->Raise();
   }
}
Example #9
0
int
setsockopt(SOCKET s, int level, int optname, const char *optval, int optlen)
{
   RTQ_NODE *n = MGenGetNode(IDLE_QUEUE);
   LPCData  *p;
   LPCReturn *r;
   SetSockOptArgs  *args;
   int       retVal;

   SocketError = 0;
   _farsetsel(flat_selector);
   p = (LPCData *) FARPKL(&n->rtqDatum);
   SetLPCData(p);
   FARPOKL(&p->service, LPC_SOCKSETOPT);
   args = (SetSockOptArgs *) p->Data;
   FARPOKL(&args->s, s);
   FARPOKL(&args->level, level);
   FARPOKL(&args->optname, optname);
   FARPOKL(&args->optlen, optlen);
   fmemcpyto(args->optval, optval, optlen);

   MGenMoveTo(IDLE_QUEUE, SEND_QUEUE);
   PostWindowsMessage();

   while ((n = MGenGetNode(REC_QUEUE)) == 0)
      Yield();

   r = (LPCReturn *) FARPKL(&n->rtqDatum);

   retVal = FARPKL(r->Data);

   // get ready for next call
   MGenMoveTo(REC_QUEUE, IDLE_QUEUE);

   return retVal;
}
Example #10
0
int main()
{
	unsigned int i=0;
	Write("\nTESTING WAIT AND BROADCAST",27,1);
	l1=CreateLock();
	c1=CreateCondition();
	c2=CreateCondition();
	Fork(clt1);
	Fork(clt2);
	Yield();
	Yield();
	Yield();
	Yield();
	Yield();
	Yield();
	/*for(i=0;i<100000;i++){}*/
	AcquireLock(l1);
	counter=counter+3;
	BroadcastCondition(c1,l1);
	ReleaseLock(l1);
	Exit(0);
}
void Manager()
{
  int MyMgrID=1;
  int MyCustID;
  int MyCookSpec; 
  int MyCookStat;
  int RmvedCookCnt=0;
  int RmvedCook[200]; 
	int a=0;
	int b=0;
	int c=0;
	int d=0;
	int i=0;
	int myOTId=PersonCount.NoOfOT;
	int CustFoodIsReady=0;
  while (1)
  {

    /*Manager should not take customers untill OT finished interaction with them*/
    Acquire(TblNeededCustLock);
		for(a=0;a<MAX_SIZE;a++)	   /*a-OTID b-CUSTID*/
		{
			for(b=0;b<MAX_SIZE;b++)
			{
				/*Print2("a=[%d]b=[%d] in for loop\n",a,b);
				Print1("TblNeededCustList[a][b]=%d outside for loop\n",TblNeededCustList[a][b]);*/
				if (TblNeededCustList[a][b]==1)
				{
					/*There are atleast some customer either waiting for food to be prepared or with food prepared and waiting for table*/
					Acquire(TotalTablesUpdateLock);
					MyCustID=b;
					/* There is a table for Customers
					Alert the customer about this*/
					if ( TotalTables>0 )
					{
						 TotalTables--;
						 Release(TotalTablesUpdateLock);
						 /*Update this table so that waiter is aware of seated customers*/
						 Acquire(TableAllotedCustLock);
						 for(c=0;c<MAX_SIZE;c++)
						 {
							if(TableAllotedCustList[c]==-1)
							{
								TableAllotedCustList[c]=MyCustID;
								TblNeededCustList[a][b]=0;
								/* There is a table for Customers
								Alert the customer about this*/
								Acquire(NeedTableLock[MyCustID]);
								Print2("Customer [%d] receives token number [%d] from the Manager\n",MyCustID,MyCustID);
								Print1("Customer[%d] is informed by the Manager - the restaurant is NOT full\n",MyCustID);
								Print1("Customer [%d] is seated at table\n",MyCustID);
								Signal(NeedTableCV[MyCustID],NeedTableLock[MyCustID]);
								Wait(NeedTableCV[MyCustID],NeedTableLock[MyCustID]);
								Release(NeedTableLock[MyCustID]);
								break;
							}
						 }
						Release(TableAllotedCustLock);
					}
					 /* if there are no tables, just give them the token number*/
					else
					 {
						/*pritnf("Customer [%d] receives token number [%d] from the Manager\n",MyCustID,MyCustID);*/
						Release(TotalTablesUpdateLock);
						Print1("Customer[%d] is informed by the Manager-the restaurant is  full\n",MyCustID);
						Print1("Customer [%d] is waiting to sit on the table\n", MyCustID);
					 }
				}
			}
    }
		a=b=c=0;
    Release(TblNeededCustLock);
        


		/*************************************************************
		* Manager as an OT START
		**************************************************************/
		i=0;
		for(i=0;i<200;i++)
		{
			Acquire(custLineLock);
			if(custLineLength>3*PersonCount.NoOfOT)
			{
				
			}
			Release(custLineLock);
		}
		
		/*************************************************************
		* Manager as an OT END
		**************************************************************/
		/* Manager as food packer*/
	
	
	Acquire(EatInCustWaitingForFoodLock);
	i=0;
	for(i=0;i<MAX_SIZE;i++)
	{
		if(EatInCustWaitingForFood[i]==1)
		{
			EatInCustWaitingForFood[i]=0;
			MyCustID=i;
			break;
		}
	}
	i=0;

	/*For (each) this customer, check if his order is ready for each type of food*/
	if(MyCustID!=-1)
		{
			CustFoodIsReady = IsCustomerFoodReady (MyCustID);
			 /* if CustFoodIsReady = 1, Food is ready and can be grabed*/
			 if (CustFoodIsReady==1)
				{
				 Acquire(GrabedFoodLock);
				 GrabedFood[myOTId][MyCustID]=1;/* 1 means food is grabed and 0 means otherwise*/
				 Release(GrabedFoodLock);
				 Print1("Manager packed food for Customer[%d]\n", MyCustID);
				 MyCustID=-1;
				 Release(EatInCustWaitingForFoodLock);
				}
			 else
				{
				 /*list of customers to whom token should be handled but shouldnt grab the food*/
				 /*this Q is as good as saying who gave token number to whom when they wanna wait*/
				  EatInCustWaitingForFood[MyCustID]=1;
					Print1("Manager gives token number to Customer[%d]\n", MyCustID);
					MyCustID=-1;
					Release(EatInCustWaitingForFoodLock);
				}
		}
	
	 else
		{
			Release(EatInCustWaitingForFoodLock);
			Acquire(ToGoCustWaitingForFoodLock);
			i=0;
			for(i=0;i<MAX_SIZE;i++)
			{
				if(ToGoCustWaitingForFood[i]==1)
				{
					ToGoCustWaitingForFood[i]=0;
					MyCustID=i;
					break;
				}
			}
			i=0;

			if(MyCustID!=-1)
			{
				CustFoodIsReady = IsCustomerFoodReady (MyCustID);
				 /* if CustFoodIsReady = 1, Food is ready and can be grabed*/
				 if (CustFoodIsReady==1)
					{
					 Acquire(GrabedFoodLock);
					 GrabedFood[myOTId][MyCustID]=1;/* 1 means food is grabed and 0 means otherwise*/
					 Release(GrabedFoodLock);
					 Print1("Manager packed the food for Customer[%d]\n", MyCustID);
					 MyCustID=-1;
					 Release(ToGoCustWaitingForFoodLock);
					}
				 else
					{
					 /*list of customers to whom token should be handled but shouldnt grab the food
					 /*this Q is as good as saying who gave token number to whom when they wanna wait*/
					  ToGoCustWaitingForFood[MyCustID]=1;
					  Print1("Manager gives token number to Customer[%d]\n",MyCustID);
						MyCustID=-1;
						Release(ToGoCustWaitingForFoodLock);
					}
			}
			else
			{
					Release(ToGoCustWaitingForFoodLock);
				/*Nothing to do
				/*Set OT status to FREE*/
			}
		}
			/*End of Manager as food packer*/

    
  /* Manager - Waiter Interaction */
  Acquire(TableAllotedCustLock);
		for(d=0;d<MAX_SIZE;d++)
		{
			if(-1!=TableAllotedCustList[d])	  /*List is not empty*/
			{
				Acquire(WaitersQLock);
				Broadcast(WaitersCV,WaitersQLock);
				Print("Manager calls back all Waiters from break\n");
				/*Print(" Manager broadcasted\n");*/
				Release(WaitersQLock);
				break;
			}
		}
		d=0;
    Release(TableAllotedCustLock);
		i=0;
		for (i=0;i<200;i++)
		{
			/*Print1("Manager yeilding%d\n",i);*/
			Yield();
		}
		i=0;
	/* Manager - Waiter Interaction End*/
	
	
		
		Acquire(AliveCustCountLock);
		if(AliveCustCount==0)
		{
			Release(AliveCustCountLock);
			Acquire(SleepingWaiterCountLock);
			/*Print1("Above while SleepingWaiterCount%d\n",SleepingWaiterCount);*/
			if (SleepingWaiterCount!=0)
			{
				while(SleepingWaiterCount!=0)
				{
					/*Print("inside while");*/
					Acquire(WaitersQLock);
					Broadcast(WaitersCV,WaitersQLock);
					Release(WaitersQLock);
					Release(SleepingWaiterCountLock);
					/*Print("Manager Broadcast\n");*/
					for (i=0;i<200;i++)
					{
						/*Print1("Manager yeilding%d\n",i);*/
						Yield();
					}
					Acquire(SleepingWaiterCountLock);
				}
			}
			Release(SleepingWaiterCountLock);
		}
		else
			Release(AliveCustCountLock);
			
		Acquire(AliveCustCountLock);
		if(AliveCustCount==0)
		{		
			Release(AliveCustCountLock);
			Acquire(ActiveOTCountLock);
			if(ActiveOTCount!=0)
			{
				/*Print1("Mgr waiting for OT, AcOT=%d\n",ActiveOTCount);*/
				while(ActiveOTCount!=0)
				{
					Release(ActiveOTCountLock);
					for (i=0;i<200;i++)
					{
						/*Print1("Manager yeilding%d\n",i);*/
						Yield();
					}
					
					Acquire(ActiveOTCountLock);
				}
			}
			Release(ActiveOTCountLock);
			if(DestroyAllLockCV==1)
			{
				/*Print1("SleepingWaiterCount%d\n",SleepingWaiterCount);*/
				Print("End of Simulation!!\n");
				Exit(1);
			}
			else
			{
				for (i=0;i<200;i++)
				{
					/*Print1("Manager yeilding%d\n",i);*/
					Yield();
				}
			}
		}
		else
		{
			Release(AliveCustCountLock);
		}
	}

    
    
}
Example #12
0
 void patient()
{
	int myIndex,k;
	int patientWaitingCount;
		
	Acquire(patientIndexLock);
	myIndex=GetMV(globalPatientIndexMV,0);
	SetMV(globalPatientIndexMV,0,myIndex+1);
	Release(patientIndexLock);

	Acquire(printLock);
	Printf1((unsigned int)"Adult Patient:",myIndex);
	Printf((unsigned int)" has entered the Doctor's Office Waiting Room.\n");
	Release(printLock);

	Acquire(wrnLineLock);
	if(GetMV(wrnStatusMV,0)==BUSY)
	{
		/*If wrn is busy, enter into line*/
		/*Printf((unsigned int)" wrnStatus=>BUSY\n");*/
		Acquire(printLock); 
		Printf1((unsigned int)"Adult Patient:",myIndex);
		Printf((unsigned int)" gets in line of the Waiting Room Nurse to get registration form.\n");
		Release(printLock); 
		 		 
		patientWaitingCount=GetMV(patientWaitingCountMV,0);
		SetMV(patientWaitingCountMV,0,patientWaitingCount+1);
		
		Acquire(printLock); 
		Printf1((unsigned int)"Adult Patient:",myIndex);
		Printf((unsigned int)" waits in line to get form\n");
		Release(printLock); 
		
		Wait(patientWaitingCV,wrnLineLock);
	} 		 
	else if(GetMV(wrnStatusMV,0)==FREE)
	{
		/* If wrn is FREE, make wrnStatus = BUSY*/
		Printf1((unsigned int)"Adult Patient:",myIndex);
		Printf((unsigned int)" finds no one is in line\n");
		SetMV(wrnStatusMV,0,BUSY);
	}
	Release(wrnLineLock);	
	Acquire(wrnLock);
	SetMV(patientTaskMV,0,GETFORM);	
	SetMV(patientGettingFormMV,0,myIndex);
	Signal(wrnWaitingCV,wrnLock); 
	Release(wrnLock);
	
	/* Allocate random values of age & name to patient*/
	Acquire(infoLock);
	/*SetMV(patientES_age,myIndex,random()%100 + 1);
	SetMV(patientES_name,myIndex,random()%26 + 1);
	SetMV(patientES_pid,myIndex,myIndex);*/
	Release(infoLock);
		
	for(k=0;k<10;k=k+1) {
			Yield();
	}
	
	Acquire(wrnLineLock);
	if(GetMV(wrnStatusMV,0) == BUSY)
	{
		/*Printf((unsigned int)"wrnStatus => Busy\n");*/
		Acquire(printLock);
		Printf1((unsigned int)"Adult Patient:",myIndex);
		Printf((unsigned int)" gets in line of the Waiting Room Nurse to submit registration form.\n");
		Release(printLock);
		patientWaitingCount=GetMV(patientWaitingCountMV,0);
		SetMV(patientWaitingCountMV,0,patientWaitingCount+1);
		Wait(patientWaitingCV,wrnLineLock);
	}
	else if(GetMV(wrnStatusMV,0) == FREE)	
	{ 
		/*Printf((unsigned int)"wrnStatus=>Free\n");*/
		SetMV(wrnStatusMV,0,BUSY);
	}
	Release(wrnLineLock);
	Acquire(wrnLock);
	SetMV(patientTaskMV,0, GIVEFORM);
	SetMV(patientGivingFormMV,0, myIndex);
	Acquire(printLock);	
	Printf1((unsigned int)"Adult patient:",myIndex);
	Printf((unsigned int)" submits the filled form to the Waiting Room Nurse.\n");
	Release(printLock);	
	Signal(wrnWaitingCV,wrnLock);
	Release(wrnLock);		 	
}
Example #13
0
int pgQueryThread::Execute()
{
	wxMutexLocker lock(m_queriesLock);

	PGresult       *result           = NULL;
	wxMBConv       &conv             = *(m_conn->conv);

	wxString       &query            = m_queries[m_currIndex]->m_query;
	int            &resultToRetrieve = m_queries[m_currIndex]->m_resToRetrieve;
	long           &rowsInserted     = m_queries[m_currIndex]->m_rowsInserted;
	Oid            &insertedOid      = m_queries[m_currIndex]->m_insertedOid;
	// using the alias for the pointer here, in order to save the result back
	// in the pgBatchQuery object
	pgSet         *&dataSet          = m_queries[m_currIndex]->m_resultSet;
	int            &rc               = m_queries[m_currIndex]->m_returnCode;
	pgParamsArray  *params           = m_queries[m_currIndex]->m_params;
	bool            useCallable      = m_queries[m_currIndex]->m_useCallable;
	pgError        &err              = m_queries[m_currIndex]->m_err;

	wxCharBuffer queryBuf = query.mb_str(conv);

	if (PQstatus(m_conn->conn) != CONNECTION_OK)
	{
		rc = pgQueryResultEvent::PGQ_CONN_LOST;
		err.msg_primary = _("Connection to the database server lost");

		return(RaiseEvent(rc));
	}

	if (!queryBuf && !query.IsEmpty())
	{
		rc = pgQueryResultEvent::PGQ_STRING_INVALID;
		m_conn->SetLastResultError(NULL, _("the query could not be converted to the required encoding."));
		err.msg_primary = _("Query string is empty");

		return(RaiseEvent(rc));
	}

	// Honour the parameters (if any)
	if (params && params->GetCount() > 0)
	{
		int    pCount = params->GetCount();
		int    ret    = 0,
		       idx    = 0;

		Oid         *pOids    = (Oid *)malloc(pCount * sizeof(Oid));
		const char **pParams  = (const char **)malloc(pCount * sizeof(const char *));
		int         *pLens    = (int *)malloc(pCount * sizeof(int));
		int         *pFormats = (int *)malloc(pCount * sizeof(int));
		// modes are used only by enterprisedb callable statement
#if defined (__WXMSW__) || (EDB_LIBPQ)
		int         *pModes   = (int *)malloc(pCount * sizeof(int));
#endif

		for (; idx < pCount; idx++)
		{
			pgParam *param = (*params)[idx];

			pOids[idx] = param->m_type;
			pParams[idx] = (const char *)param->m_val;
			pLens[idx] = param->m_len;
			pFormats[idx] = param->GetFormat();
#if defined (__WXMSW__) || (EDB_LIBPQ)
			pModes[idx] = param->m_mode;
#endif
		}

		if (useCallable)
		{
#if defined (__WXMSW__) || (EDB_LIBPQ)
			wxLogInfo(wxString::Format(
			              _("using an enterprisedb callable statement (queryid:%ld, threadid:%ld)"),
			              (long)m_currIndex, (long)GetId()));
			wxString stmt = wxString::Format(wxT("pgQueryThread-%ld-%ld"), this->GetId(), m_currIndex);
			PGresult *res = PQiPrepareOut(m_conn->conn, stmt.mb_str(wxConvUTF8),
			                              queryBuf, pCount, pOids, pModes);

			if( PQresultStatus(res) != PGRES_COMMAND_OK)
			{
				rc = pgQueryResultEvent::PGQ_ERROR_PREPARE_CALLABLE;
				err.SetError(res, &conv);

				PQclear(res);

				goto return_with_error;
			}

			ret = PQiSendQueryPreparedOut(m_conn->conn, stmt.mb_str(wxConvUTF8),
			                              pCount, pParams, pLens, pFormats, 1);

			if (ret != 1)
			{
				rc = pgQueryResultEvent::PGQ_ERROR_EXECUTE_CALLABLE;

				m_conn->SetLastResultError(NULL, _("Failed to run PQsendQuery in pgQueryThread"));
				err.msg_primary = wxString(PQerrorMessage(m_conn->conn), conv);

				PQclear(res);
				res = NULL;

				goto return_with_error;
			}

			PQclear(res);
			res = NULL;
#else
			rc = -1;
			wxASSERT_MSG(false,
			             _("the program execution flow must not reach to this point in pgQueryThread"));

			goto return_with_error;
#endif
		}
		else
		{
			// assumptions: we will need the results in text format only
			ret = PQsendQueryParams(m_conn->conn, queryBuf, pCount, pOids, pParams, pLens, pFormats, 0);

			if (ret != 1)
			{
				rc = pgQueryResultEvent::PGQ_ERROR_SEND_QUERY;

				m_conn->SetLastResultError(NULL,
				                           _("Failed to run PQsendQueryParams in pgQueryThread"));

				err.msg_primary = _("Failed to run PQsendQueryParams in pgQueryThread.\n") +
				                  wxString(PQerrorMessage(m_conn->conn), conv);

				goto return_with_error;
			}
		}
		goto continue_without_error;

return_with_error:
		{
			free(pOids);
			free(pParams);
			free(pLens);
			free(pFormats);
#if defined (__WXMSW__) || (EDB_LIBPQ)
			free(pModes);
#endif
			return (RaiseEvent(rc));
		}
	}
	else
	{
		// use the PQsendQuery api in case, we don't have any parameters to
		// pass to the server
		if (!PQsendQuery(m_conn->conn, queryBuf))
		{
			rc = pgQueryResultEvent::PGQ_ERROR_SEND_QUERY;

			err.msg_primary = _("Failed to run PQsendQueryParams in pgQueryThread.\n") +
			                  wxString(PQerrorMessage(m_conn->conn), conv);

			return(RaiseEvent(rc));
		}
	}

continue_without_error:
	int resultsRetrieved = 0;
	PGresult *lastResult = 0;

	while (true)
	{
		// This is a 'joinable' thread, it is not advisable to call 'delete'
		// function on this.
		// Hence - it does not make sense to use the function 'testdestroy' here.
		// We introduced the 'CancelExecution' function for the same purpose.
		//
		// Also, do not raise event when the query execution is cancelled to
		// avoid the bugs introduced to handle events by the event handler,
		// which is missing or being deleted.
		//
		// It will be responsibility of the compononent, using the object of
		// pgQueryThread, to take the required actions to take care of the
		// issue.
		if (m_cancelled)
		{
			m_conn->CancelExecution();
			rc = pgQueryResultEvent::PGQ_EXECUTION_CANCELLED;

			err.msg_primary = _("Execution Cancelled");

			if (lastResult)
			{
				PQclear(lastResult);
				lastResult = NULL;
			}
			AppendMessage(_("Query-thread execution cancelled...\nthe query is:"));
			AppendMessage(query);

			return rc;
		}

		if ((rc = PQconsumeInput(m_conn->conn)) != 1)
		{
			if (rc == 0)
			{
				err.msg_primary = wxString(PQerrorMessage(m_conn->conn), conv);
			}
			if (PQstatus(m_conn->conn) == CONNECTION_BAD)
			{
				err.msg_primary = _("Connection to the database server lost");
				rc = pgQueryResultEvent::PGQ_CONN_LOST;
			}
			else
			{
				rc = pgQueryResultEvent::PGQ_ERROR_CONSUME_INPUT;
			}

			return(RaiseEvent(rc));
		}

		if (PQisBusy(m_conn->conn))
		{
			Yield();
			this->Sleep(10);

			continue;
		}

		// if resultToRetrieve is given, the nth result will be returned,
		// otherwise the last result set will be returned.
		// all others are discarded
		PGresult *res = PQgetResult(m_conn->conn);

		if (!res)
			break;

		if((PQresultStatus(res) == PGRES_NONFATAL_ERROR) ||
		        (PQresultStatus(res) == PGRES_FATAL_ERROR) ||
		        (PQresultStatus(res) == PGRES_BAD_RESPONSE))
		{
			result = res;
			err.SetError(res, &conv);

			// Wait for the execution to be finished
			// We need to fetch all the results, before sending the error
			// message
			do
			{
				if (PQconsumeInput(m_conn->conn) != 1)
				{
					if (m_cancelled)
					{
						rc = pgQueryResultEvent::PGQ_EXECUTION_CANCELLED;

						// Release the result as the query execution has been cancelled by the
						// user
						if (result)
							PQclear(result);

						return rc;
					}
					goto out_of_consume_input_loop;
				}

				if ((res = PQgetResult(m_conn->conn)) == NULL)
				{
					goto out_of_consume_input_loop;
				}
				// Release the temporary results
				PQclear(res);
				res = NULL;

				if (PQisBusy(m_conn->conn))
				{
					Yield();
					this->Sleep(10);
				}
			}
			while (true);

			break;
		}

#if defined (__WXMSW__) || (EDB_LIBPQ)
		// there should be 2 results in the callable statement - the first is the
		// dummy, the second contains our out params.
		if (useCallable)
		{
			PQclear(res);
			result = PQiGetOutResult(m_conn->conn);
		}
#endif
		if (PQresultStatus(res) == PGRES_COPY_IN)
		{
			rc = PGRES_COPY_IN;
			PQputCopyEnd(m_conn->conn, "not supported by pgadmin");
		}

		if (PQresultStatus(res) == PGRES_COPY_OUT)
		{
			int copyRc;
			char *buf;
			int copyRows = 0;
			int lastCopyRc = 0;

			rc = PGRES_COPY_OUT;

			AppendMessage(_("query returned copy data:\n"));

			while((copyRc = PQgetCopyData(m_conn->conn, &buf, 1)) >= 0)
			{
				if (buf != NULL)
				{
					if (copyRows < 100)
					{
						wxString str(buf, conv);
						wxCriticalSectionLocker cs(m_criticalSection);
						m_queries[m_currIndex]->m_message.Append(str);

					}
					else if (copyRows == 100)
						AppendMessage(_("Query returned more than 100 copy rows, discarding the rest...\n"));

					PQfreemem(buf);
				}
				if (copyRc > 0)
					copyRows++;

				if (m_cancelled)
				{
					m_conn->CancelExecution();
					rc = pgQueryResultEvent::PGQ_EXECUTION_CANCELLED;

					return -1;
				}
				if (lastCopyRc == 0 && copyRc == 0)
				{
					Yield();
					this->Sleep(10);
				}
				if (copyRc == 0)
				{
					if (!PQconsumeInput(m_conn->conn))
					{
						if (PQstatus(m_conn->conn) == CONNECTION_BAD)
						{
							err.msg_primary = _("Connection to the database server lost");
							rc = pgQueryResultEvent::PGQ_CONN_LOST;
						}
						else
						{
							rc = pgQueryResultEvent::PGQ_ERROR_CONSUME_INPUT;

							err.msg_primary = wxString(PQerrorMessage(m_conn->conn), conv);
						}
						return(RaiseEvent(rc));
					}
				}
				lastCopyRc = copyRc;
			}

			res = PQgetResult(m_conn->conn);

			if (!res)
				break;
		}

		resultsRetrieved++;
		if (resultsRetrieved == resultToRetrieve)
		{
			result = res;
			insertedOid = PQoidValue(res);
			if (insertedOid && insertedOid != (Oid) - 1)
				AppendMessage(wxString::Format(_("query inserted one row with oid %d.\n"), insertedOid));
			else
				AppendMessage(wxString::Format(wxPLURAL("query result with %d row will be returned.\n", "query result with %d rows will be returned.\n",
				                                        PQntuples(result)), PQntuples(result)));
			continue;
		}

		if (lastResult)
		{
			if (PQntuples(lastResult))
				AppendMessage(wxString::Format(wxPLURAL("query result with %d row discarded.\n", "query result with %d rows discarded.\n",
				                                        PQntuples(lastResult)), PQntuples(lastResult)));
			PQclear(lastResult);
		}
		lastResult = res;
	}
out_of_consume_input_loop:

	if (!result)
		result = lastResult;

	err.SetError(result, &conv);

	AppendMessage(wxT("\n"));

	rc = PQresultStatus(result);
	if (rc == PGRES_TUPLES_OK)
	{
		dataSet = new pgSet(result, m_conn, conv, m_conn->needColQuoting);
		dataSet->MoveFirst();
	}
	else if (rc == PGRES_COMMAND_OK)
	{
		char *s = PQcmdTuples(result);
		if (*s)
			rowsInserted = atol(s);
	}
	else if (rc == PGRES_FATAL_ERROR ||
	         rc == PGRES_NONFATAL_ERROR ||
	         rc == PGRES_BAD_RESPONSE)
	{
		if (result)
		{
			AppendMessage(wxString(PQresultErrorMessage(result), conv));
			PQclear(result);
			result = NULL;
		}
		else
		{
			AppendMessage(wxString(PQerrorMessage(m_conn->conn), conv));
		}

		return(RaiseEvent(rc));
	}

	insertedOid = PQoidValue(result);
	if (insertedOid == (Oid) - 1)
		insertedOid = 0;

	return(RaiseEvent(1));
}
Example #14
0
int pgQueryThread::execute()
{
	rowsInserted = -1L;

	if (!conn->conn)
		return(raiseEvent(0));

	wxCharBuffer queryBuf = query.mb_str(*conn->conv);
	if (!queryBuf && !query.IsEmpty())
	{
		conn->SetLastResultError(NULL, _("The query could not be converted to the required encoding."));
		return(raiseEvent(0));
	}

	if (!PQsendQuery(conn->conn, queryBuf))
	{
		conn->SetLastResultError(NULL);
		conn->IsAlive();
		return(raiseEvent(0));
	}
	int resultsRetrieved = 0;
	PGresult *lastResult = 0;
	while (true)
	{
		if (TestDestroy())
		{
			if (rc != -3)
			{
				if (!PQrequestCancel(conn->conn)) // could not abort; abort failed.
					return(raiseEvent(-1));

				rc = -3;
			}
		}
		if (!PQconsumeInput(conn->conn))
			return(raiseEvent(0));
		if (PQisBusy(conn->conn))
		{
			Yield();
			this->Sleep(10);
			continue;
		}

		// If resultToRetrieve is given, the nth result will be returned,
		// otherwise the last result set will be returned.
		// all others are discarded
		PGresult *res = PQgetResult(conn->conn);

		if (!res)
			break;

		resultsRetrieved++;
		if (resultsRetrieved == resultToRetrieve)
		{
			result = res;
			insertedOid = PQoidValue(res);
			if (insertedOid && insertedOid != (OID) - 1)
				appendMessage(wxString::Format(_("Query inserted one row with OID %d.\n"), insertedOid));
			else
				appendMessage(wxString::Format(wxPLURAL("Query result with %d row will be returned.\n", "Query result with %d rows will be returned.\n",
				                                        PQntuples(result))));
			continue;
		}
		if (lastResult)
		{
			if (PQntuples(lastResult))
				appendMessage(wxString::Format(wxPLURAL("Query result with %d row discarded.\n", "Query result with %d rows discarded.\n",
				                                        PQntuples(lastResult))));
			PQclear(lastResult);
		}
		lastResult = res;
	}

	if (!result)
		result = lastResult;

	conn->SetLastResultError(result);

	appendMessage(wxT("\n"));
	rc = PQresultStatus(result);
	insertedOid = PQoidValue(result);
	if (insertedOid == (OID) - 1)
		insertedOid = 0;

	if (rc == PGRES_TUPLES_OK)
	{
		dataSet = new pgSet(result, conn, *conn->conv, conn->needColQuoting);
		dataSet->MoveFirst();
	}
	else if (rc == PGRES_COMMAND_OK)
	{
		char *s = PQcmdTuples(result);
		if (*s)
			rowsInserted = atol(s);
	}
	else if (rc == PGRES_FATAL_ERROR)
	{
		appendMessage(conn->GetLastError() + wxT("\n"));
	}
	return(raiseEvent(1));
}
Example #15
0
void main()
{
 int input;
 int q,c,i;

Printf("\n1 general interaction between two threads\n");
 Printf("\n2 threads trying to work on lock that has not been created\n");
 Printf("\n3 Broadcast all the waiting threads\n");
 Printf("\n4 signal done by thread but no one waiting..\n");
 Printf("\n5 many threads waiting.....but only one signal\n");
 Printf("\n6 one thread waiting on some lock and other thread signals it on some other lock..\n");
 Printf("\n7 lock number is greater than max locks spacei.e 100\n");
 Printf("\n8 forking more than 100 threads in 1 proc..which is beyond the set limit ... so error\n");
 Printf("\n9 Two execs..and it should call 2 process and in which 2 threads tries to acquire each other's lock..\n");
 Printf("\n10 lock acquired by one thread so all other should wait for the thread to release the lock.. \n");
 Printf("\n11 testing destroy lock and destroy CV system call	 \n");
 Printf("\n12 running 2 carl jr proccesses with  \nCUSTOMERS:30 \n OT:5\n COOKS:3\nWAITER:5\nMANAGER:1\n");
 input= Scanf();

 switch ( input)
 {
 case 1:
   q=  Exec("../test/test1",13);
   break;
 case 2:
	  q=  Exec("../test/test2",13);
   break;
 case 3:
	  q=  Exec("../test/test3",13);
   break;
 case 4:
	  q=  Exec("../test/test4",13);
   break;
 case 5:
	  q=  Exec("../test/test5",13);
   break;
 case 6:
	  q=   Exec("../test/test6",13);
   break;
 case 7:
	  q=  Exec("../test/test7",13);
   break;
 case 8:
	  q= Exec("../test/test8",13);
   break;
 case 9:
	  q= Exec("../test/test9",13);
	  c=  Exec("../test/test10",14);
	  Yield();
   break;
 case 10:
	  q= Exec("../test/test11",14);
   break;

 case 11:

	 q= Exec("../test/test12",14);

	 break;
 case 12:

	 q= Exec("../test/carljr",14);
	 c= Exec("../test/carljr",14);
	 break;
}
for(i=0;i<10000;i++)
{
 Yield();
}

}
Example #16
0
//Main entry point.
int _tmain(int argc, _TCHAR* argv[])
{

	

	ZeroMemory(tskbuffer, sizeof(wchar_t) * 2048);
	m_logger = new AlCLogger(L"c://temp//taskmgr.log", true);

	//Read in the task file...
	//any tasks matching names within this file, will be auto killed!
	wchar_t* fileName = L"C:\\Alwyn\\dev\\c\\AlTaskManager\\Release\\taskmanager.ini";
	int taskCount = GetPrivateProfileInt(L"tasks", L"tasks.count", 0, fileName);

	if (taskCount < 1)
	{
		m_logger->debug("No tasks to manage...\r\n");
		goto exit;
	}

	m_Task_Thread = new AlTaskThread(m_logger);

	m_Task_Thread->tasksCount = taskCount;
	m_Task_Thread->tasks = new wchar_t*[m_Task_Thread->tasksCount];

	m_Task_Thread->timeOut = GetPrivateProfileInt(L"tasks", L"tasks.timeout", 1, fileName);

	for (int i=0; i<m_Task_Thread->tasksCount; i++)
	{
		//Buildup task name...
		swprintf_s(tskbuffer, L"tasks.%i\0", i+1);
		m_Task_Thread->tasks[i] = new wchar_t[1024];
		ZeroMemory(m_Task_Thread->tasks[i], sizeof(wchar_t) * 1024);

		GetPrivateProfileString(L"tasks", tskbuffer, L"", m_Task_Thread->tasks[i], sizeof(wchar_t) * 1024, fileName);
		_wcslwr_s(m_Task_Thread->tasks[i], sizeof(wchar_t) * 1024);

		swprintf_s(tskbuffer, L"Got a task name: #%i, '%s'\r\n\0", i, m_Task_Thread->tasks[i]);
		m_logger->debug(tskbuffer);
	}

	//Default stack size 64Kb
	m_Task_Thread->stackSize = 1024 * 64;
	m_logger->debug("Starting task manager..\r\n");
	m_Task_Thread->start();
	
	int v = 0;

	while (v != 9)
	{
		cout << "9 = quit task manager.\n";
		cin >> v;
	}


	m_Task_Thread->stop = true;
	while (!m_Task_Thread->completed)
	{
		Sleep(1);
		Yield();
	}


	m_logger->debug("Task manager has quit.\r\n");

exit:


	SAFE_DEL(m_Task_Thread);
	SAFE_DEL(m_logger);
	

	
	return 0;
}
Example #17
0
void ScreenshotCommand::Capture(wxString filename,
                          wxWindow *window,
                          int x, int y, int width, int height,
                          bool bg)
{
   if (window) {
      if (window->IsTopLevel()) {
         window->Raise();
      }
      else {
         wxGetTopLevelParent(window)->Raise();
      }
   }

   Yield();

   int screenW, screenH;
   wxDisplaySize(&screenW, &screenH);
   wxBitmap full(screenW, screenH);

   wxScreenDC screenDC;
   wxMemoryDC fullDC;

   // We grab the whole screen image since there seems to be a problem with
   // using non-zero source coordinates on OSX.  (as of wx2.8.9)
   fullDC.SelectObject(full);
   fullDC.Blit(0, 0, screenW, screenH, &screenDC, 0, 0);
   fullDC.SelectObject(wxNullBitmap);

   wxRect r(x, y, width, height);

   // Ensure within bounds (x/y are negative on Windows when maximized)
   r.Intersect(wxRect(0, 0, screenW, screenH));

   // Convert to screen coordinates if needed
   if (window && window->GetParent() && !window->IsTopLevel()) {
      r.SetPosition(window->GetParent()->ClientToScreen(r.GetPosition()));
   }

   // Extract the actual image
   wxBitmap part = full.GetSubBitmap(r);

   // Add a background
   if (bg && mBackground) {
      wxRect b = GetBackgroundRect();

      wxBitmap back(width + b.width, height + b.height);
      fullDC.SelectObject(back);

      fullDC.SetBackground(wxBrush(mBackColor, wxSOLID));
      fullDC.Clear();

      fullDC.DrawBitmap(part, b.x, b.y);
      fullDC.SelectObject(wxNullBitmap);

      part = back;
   }

   // Save the final image
   wxImage image = part.ConvertToImage();
   if (image.SaveFile(filename)) {
      mOutput->Status(_("Saved ") + filename);
   }
   else {
      mOutput->Error(_("Error trying to save file: ") + filename);
   }

   ::wxBell();
}
Example #18
0
void infinity(){
    int i = 0;
    for (; ;) Yield();
}
Example #19
0
/** Entry
  *
  *
  */
void* LC3RunThread::Entry()
{
    ///TODO consider writing this without rewriting next_line/prev_line.
    int depth = 0;
    lc3_instr instr;
    bool interrupt_begin = false;

    state.halted = 0;

    switch(run_mode)
    {
    case RUNMODE_RUN:
        while(!state.halted)
        {
            lc3_step(state);
            if (TestDestroy()) break;
            Yield();
        }
        break;
    case RUNMODE_RUNFOR:
        if (runtime > 0)
            lc3_run(state, runtime);
        else
            lc3_rewind(state, -runtime);
        break;
    case RUNMODE_STEP:
        lc3_step(state);
        break;
    case RUNMODE_BACK:
        lc3_back(state);
        break;
    case RUNMODE_FINISH:
        depth = 1;
    case RUNMODE_NEXTLINE:
        // Subroutine depth
        do
        {
            // Get Next Instruction.
            instr = lc3_decode(state, state.mem[state.pc]);
            // So if we get a JSR/JSRR or if we get a TRAP and true traps are enabled
            if (instr.data.opcode == JSR_INSTR || (instr.data.opcode == TRAP_INSTR && state.true_traps))
                depth++;

            // If we get a RET instruction JMP R7
            if (instr.data.opcode == JMP_INSTR && instr.jmp.base_r == 7)
                depth--;

            // If we get an RTI instruction
            if (instr.data.opcode == RTI_INSTR)
                depth--;

            // Execute
            lc3_step(state);

            // If we got interrupted
            if (state.interrupt_enabled && state.undo_stack.back().changes == LC3_INTERRUPT_BEGIN)
                depth++;

            if (TestDestroy()) break;
            Yield();
        }
        while (depth != 0 && !state.halted);
        break;
    case RUNMODE_PREVLINE:
        // Subroutine depth
        depth = 0;

        do
        {
            if (!state.undo_stack.empty())
            {
                lc3_state_change& last = state.undo_stack.back();
                // Can't backstep through interrupt
                if (last.changes == LC3_INTERRUPT_BEGIN)
                    break;

                // Get rid of all processed interrupts.
                while (last.changes == LC3_INTERRUPT && !state.undo_stack.empty())
                {
                    lc3_back(state);
                    last = state.undo_stack.back();
                    if (TestDestroy()) break;
                    Yield();
                }
            }

            // Execute (Have to do this first you can't assume mem[pc - 1] was the last
            // instruction due to jumps.
            lc3_back(state);
            // Get the instruction that got you where you are.
            lc3_instr instr = lc3_decode(state, state.mem[state.pc]);
            // If we get a RET instruction JMP R7
            if (instr.data.opcode == JMP_INSTR && instr.jmp.base_r == 7)
                depth++;
            // So if we get a JSR/JSRR or if we get a TRAP and true traps are enabled
            if (instr.data.opcode == JSR_INSTR || (instr.data.opcode == TRAP_INSTR && state.true_traps))
                depth--;
            if (TestDestroy()) break;
            Yield();
            // Don't have to handle interrupts here...
        }
        while (depth != 0 && !state.halted && !state.undo_stack.empty());
        break;
    case RUNMODE_REWIND:
        // Do this until no more changes.
        while (!state.undo_stack.empty() && !interrupt_begin)
        {
            lc3_state_change& last = state.undo_stack.back();
            interrupt_begin = (last.changes == LC3_INTERRUPT_BEGIN);
            // Backstep
            lc3_back(state);

            if (TestDestroy()) break;
            Yield();
        }
        break;
    }

    wxQueueEvent(frame, new wxThreadEvent(wxEVT_COMMAND_RUNTHREAD_COMPLETED));

    return NULL;
}
Example #20
0
void President()
{
  int presidentNumberOfCalls=0; /* keep count of total number of calls made by the president */
  int checkCorrectOperatorP;
  int waitingTime;
  int condnToWait;
  int phoneToUse, gotPhone,i,j;
  int operatorToUse;
  int talkingTime;
  int phoneStatus_i;
  int num;
  char lockName[30];
  char condName1[30];
  char condName2[30];
  int presidentStatus;
  int phoneStatus;
  char printing[50];
  int lockID1, lockID2, lockID3, lockID4, lockID5, lockID6, condID1, condID2, condID3, condID4;
  int indOpLock[20], waitForOperVerCV[20], waitForCallerCV[20];
  int activate, authMechanism, freeOperators, operatorStatus;



  /* Create or get access to some shared variables, locks, conditions */
  presidentStatus = CreateSharedInt("presidentStatus",15,1);
  phoneStatus = CreateSharedInt("phoneStatus",11,NOOFPHONES);
  lockID1 = CreateLock("phoneLock",10);                  /* obtain a master lock for all phones */
  freeOperators = CreateSharedInt("freeOperators",13,1);
  operatorStatus = CreateSharedInt("operatorStatus",14,Nop);
  activate = CreateSharedInt("activate",sizeof("activate"),Nop);
  authMechanism = CreateSharedInt("authMechanism",sizeof("authMechanism"),Nop);


  lockID2 = CreateLock("GlobalOpLock",sizeof("globaloplock"));     /* obtain a master lock for all the operators */
  lockID3 = CreateLock("visitorCountLock",17);     /* obtain a lock to keep track of the number of visitors permitted to make a call */
  lockID4 = CreateLock("NumSenators",12);
  lockID5 = CreateLock("NumVisitors",12);
  lockID6 = CreateLock("NumOperators",13);
 /*  displayLock = CreateLock("DispLock",7); */
  /* Lock **individualOperatorLock; */                            /* obtain an individual lock for every operator */
  condID1 = CreateCondition("presiNeedsPhone",16); /* condition variable for the condition that president needs phone */
  condID2 = CreateCondition("senatorNeedsPhone",18);     /* condition variable for the condition that senator needs phone */
  condID3 = CreateCondition("visitorNeedsPhone",18);     /* condition variable for the condition that visitor  needs phone */
  condID4 = CreateCondition("processCustomer",16);         /* condition variable to allow president/senator/visitor to make a call */
  for (i=0;i<Nop;i++)
    {
     Concatenate("OperatorLock",sizeof("OperatorLock"),i,lockName);
     Concatenate("waitForOpVer",sizeof("waitForOpVer"),i,condName1);
     Concatenate("waitForCaller",sizeof("waitForCaller"),i,condName2); 
     indOpLock[i] = CreateLock(lockName,sizeof(lockName));
     waitForOperVerCV[i] = CreateCondition(condName1,sizeof(condName1));
     waitForCallerCV[i] = CreateCondition(condName2,sizeof(condName2));
    } 

	 while(presidentNumberOfCalls<3)
    {
		 WriteMe("President Going to speak for the ");WriteNum(presidentNumberOfCalls);WriteMe("th time\n");
      condnToWait = FALSE;
      phoneToUse = 0;

      AcquireLock(lockID1);

      SetSharedInt(presidentStatus, 0, 1); /* presidentStatus = 1; */

      /* loop for the president to keep waiting even if a single phone is busy */
      do
	  {	 
		  /*
		  for(i=0;i<NOOFPHONES;i++)
		    {
			 phoneStatus_i = GetSharedInt(phoneStatus,i);
		     if(phoneStatus_i == BUSY)
				{
				 condnToWait = TRUE;
				 break;
				}
		    } */
			i = GetZeroIndex(phoneStatus);

		if(i==NOOFPHONES)
		   condnToWait=FALSE;
		else
			condnToWait = TRUE;
	
		if(condnToWait==TRUE)
		  WaitCV(condID1,lockID1);
	
	  }while(condnToWait==TRUE);
	  	
      /* all phones are free now */
      SetSharedInt(phoneStatus, phoneToUse, BUSY); /* phoneStatus[phoneToUse] = BUSY;*/
      /* president has obtained a phone now */
      ReleaseLock(lockID1);      
      /* Need to get an operator */
      AcquireLock(lockID2);
      /* loop to wait till an operator is available */
	  	
      while(GetSharedInt(freeOperators,0)==0)
	    WaitCV(condID4,lockID2);
	  	
	  /* president has to wait if there are no free operators available */
      /* Some operator is available. Though I don't know who it is yet, let us find out    */    
      /*
	  for(j=0;j<Nop;j++)
	  {
	  if(GetSharedInt(operatorStatus,j)==FREE)
	    {
	      operatorToUse = j;
	      break;
	    }
	 }
	 */
	 operatorToUse = GetOneIndex(operatorStatus);
      /* operator obtained */
      /* check if the operator to whom president goes for authentication is same as the one who permits him/her to make a call. */
      checkCorrectOperatorP = operatorToUse;
      AcquireLock(indOpLock[operatorToUse]);
      SetSharedInt(activate, operatorToUse, 2);
      SetSharedInt(operatorStatus, operatorToUse, BUSY);
      SetSharedInt(freeOperators, 0, GetSharedInt(freeOperators, 0) - 1);
	  ReleaseLock(lockID2);
      SetSharedInt(authMechanism, operatorToUse, 1); /* 1 for President | 2 for Senators | 3 for Visitors */
	 
      /* If operator is sleeping, wake up */
	  SignalCV(waitForCallerCV[operatorToUse],indOpLock[operatorToUse]);
	  while(GetSharedInt(activate,operatorToUse)==2)
	      WaitCV(waitForOperVerCV[operatorToUse],indOpLock[operatorToUse]); 
      ReleaseLock(indOpLock[operatorToUse]);  
      if(GetSharedInt(activate,operatorToUse)==0) /* President is denied access to phone.But this will never happen as there is only one president and we assume that his/her ID is never faked */
	  {
	  /*  printf("President is denied access to Phone failing authentication!\n"); */
		Write("President is denied access to Phone failing authentication!\n",sizeof("President is denied access to Phone failing authentication!\n"),1);
	  }
      else if(GetSharedInt(activate, operatorToUse)==1) /* operator succesfully authenticates the identity of the president */
	 {
	  /* Now Talk */
	  talkingTime = RandomFunction(20); /* randomly generate the amount of time the president is talking */
          /* loop for the president to talk on the phone for the randomly generated time period */
	  for (j=1;j<=talkingTime;j++){
	    /*printf("President \t  %d \t\t %d/%d units \t %d \t\t %d \t    ACCEPTED       NOTAPPLICABLE - verified by operator %d \n",phoneToUse+1,j,talkingTime,operatorToUse+1,presidentNumberOfCalls+1,checkCorrectOperatorP+1);*/
		/*AcquireLock(displayLock); */
		Write("President \t ",13,1);
	    num = phoneToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("\t\t ",5,1);	    
	    itoa(printing,10,j);
	    Write(printing,sizeof(printing),1);
	    Write("/",1,1);
	    num=talkingTime;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" units \t ",10,1);
	    num=operatorToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t\t ",6,1);
	    num=presidentNumberOfCalls+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t   ACCEPTED      NOTAPPLICABLE - verified by operator ",56,1);
	    num=checkCorrectOperatorP+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \n",3,1);
		/*ReleaseLock(displayLock);*/
	   /* Yield();*/
	  }
	  /* president is done talking */	  
	  /* Set the status to be free */
	  AcquireLock(lockID1);
	  SetSharedInt(phoneStatus, phoneToUse, FREE);
	  SetSharedInt(presidentStatus,0,0);
	  BroadcastCV(condID2,lockID1); /* wake up all the senators waiting to talk */
	  BroadcastCV(condID3,lockID1); /* wake up all the visitors waiting to talk */
	  ReleaseLock(lockID1);
	}
      /* president goes away  */
      /* president waits for a random amount of time before coming back to make the next call. Remember maximum number of calls allowed is 5 */
      waitingTime = RandomFunction(4);
      for(j=0;j<waitingTime;j++)
	{
	  Yield();
	}
      presidentNumberOfCalls++; /* increment the number of calls made by the president */
    }
  Exit(0);
}
Example #21
0
void Visitor() /* code block to perform visitor operation */
{
  int condnToWait,who,i,j, num;
  int talkingTime;
  int checkCorrectOperatorV;
  int phoneToUse,gotPhone;
  int thisActivate;
  int operatorToUse;
  int callPresident;

/* Some common parameters */


  char lockName[30];
  char condName1[30];
  char condName2[30];
  int presidentStatus;
  int phoneStatus;
  char printing[50];
  int lockID1, lockID2, lockID3, lockID4, lockID5, lockID6, condID1, condID2, condID3, condID4;
  int indOpLock[20], waitForOperVerCV[20], waitForCallerCV[20];
  int activate, authMechanism, freeOperators, operatorStatus;
  int repositoryMoney;
 

  presidentStatus = CreateSharedInt("presidentStatus",15,1);
  phoneStatus = CreateSharedInt("phoneStatus",11,NOOFPHONES);
  freeOperators = CreateSharedInt("freeOperators",13,1);
  operatorStatus = CreateSharedInt("operatorStatus",14,Nop);
  activate = CreateSharedInt("activate",sizeof("activate"),Nop);
  authMechanism = CreateSharedInt("authMechanism",sizeof("authMechanism"),Nop);
  repositoryMoney = CreateSharedInt("repositoryMoney",sizeof("repositoryMoney"),Nop);
 
  

  lockID1 = CreateLock("phoneLock",10);                  /* obtain a master lock for all phones */
  lockID2 = CreateLock("GlobalOpLock",12);     /* obtain a master lock for all the operators */
  lockID3 = CreateLock("visitorCountLock",17);     /* obtain a lock to keep track of the number of visitors permitted to make a call */
  lockID4 = CreateLock("NumSenators",12);
  lockID5 = CreateLock("NumVisitors",12);
  lockID6 = CreateLock("NumOperators",13);
  /*  displayLock = CreateLock("DispLock",7); */
  /* Lock **individualOperatorLock; */                            /* obtain an individual lock for every operator */
  condID1 = CreateCondition("presiNeedsPhone",16); /* condition variable for the condition that president needs phone */
  condID2 = CreateCondition("senatorNeedsPhone",18);     /* condition variable for the condition that senator needs phone */
  condID3 = CreateCondition("visitorNeedsPhone",18);     /* condition variable for the condition that visitor  needs phone */
  condID4 = CreateCondition("processCustomer",16);         /* condition variable to allow president/senator/visitor to make a call */
  for (i=0;i<Nop;i++)
    {
      Concatenate("OperatorLock",sizeof("OperatorLock"),i,lockName);
      Concatenate("waitForOpVer",sizeof("waitForOpVer"),i,condName1);
      Concatenate("waitForCaller",sizeof("waitForCaller"),i,condName2); 
      indOpLock[i] = CreateLock(lockName,sizeof(lockName));
      waitForOperVerCV[i] = CreateCondition(condName1,sizeof(condName1));
      waitForCallerCV[i] = CreateCondition(condName2,sizeof(condName2));
    } 
  
  
  
  /* End of common parameters */

  AcquireLock(lockID5);
  who = NumVisitor;
  NumVisitor++;
  ReleaseLock(lockID5);
  AcquireLock(lockID1);
  /* loop to check if the president or senator is waiting. If any one is waiting, then visitor has to wait before he/she can make a call. Otherwise visitor can go ahead */
  do
    {
      condnToWait = TRUE;      
      if(GetSharedInt(presidentStatus,0) == 1)
		condnToWait = TRUE;
      /* Check if some senator is already waiting! */
      else if(CheckCondWaitQueue(condID2)==1)
		{
		  /* Bad luck, there seems to be a senator.  */
		  condnToWait = TRUE;
		}
      else
		{
		  /*
	  for(i=0;i<NOOFPHONES;i++)
	    {
	      if(GetSharedInt(phoneStatus,i)==FREE)
		   {
			  phoneToUse = i;
			  SetSharedInt(phoneStatus,i,BUSY);
			  condnToWait = FALSE;
			  break;
		   }
	    }	*/
		phoneToUse = GetOneIndex(phoneStatus);
		if(phoneToUse!=NOOFPHONES)
			condnToWait = FALSE;
	}
      if(condnToWait)
	WaitCV(condID3,lockID1); /* visitor waits if there is a president or a senator already waitng to make a call. */
    }while(condnToWait);
  ReleaseLock(lockID1);
  /* Visitor has got a phone */
  /* Need to get an operator now */
  AcquireLock(lockID2);
  while(GetSharedInt(freeOperators,0)==0)
    WaitCV(condID4,lockID2);
  /* visitor has to wait if there are no free operators available */
  /* Some operator is available. Though I don't know who it is. Let us find out.   */ 
  /*
  for(j=0;j<Nop;j++)
    {
      if(GetSharedInt(operatorStatus,j)==FREE)
	{
	  operatorToUse = j;
	  break;
	}
    } */
	operatorToUse = GetOneIndex(operatorStatus);
  /* operator obtained */
  checkCorrectOperatorV = operatorToUse; /* check if the operator to whom the visitor pays money is the same as the one the permits/denies the visitor to make a call */
  AcquireLock(indOpLock[operatorToUse]);
  SetSharedInt(activate, operatorToUse, 2);
  SetSharedInt(operatorStatus, operatorToUse, BUSY);
  SetSharedInt(freeOperators, 0, GetSharedInt(freeOperators, 0) - 1);
  ReleaseLock(lockID2);
  SetSharedInt(authMechanism, operatorToUse, 3);  /* 1 for President | 2 for Senators | 3 for Visitors */
  SetSharedInt(repositoryMoney, operatorToUse, ((RandomFunction(100)-1)>80)?0:1); /* randomly generate whether the visitor pays $1 or not */
  /* If operator is sleeping, wake up */

  SignalCV(waitForCallerCV[operatorToUse],indOpLock[operatorToUse]);
  SignalCV(waitForCallerCV[operatorToUse],indOpLock[operatorToUse]);
  while(GetSharedInt(activate,operatorToUse)==2)
	  WaitCV(waitForOperVerCV[operatorToUse],indOpLock[operatorToUse]);
  thisActivate=0;
  thisActivate=GetSharedInt(activate, operatorToUse);  
  ReleaseLock(indOpLock[operatorToUse]);
  if (thisActivate==0) 
    {
	  /* visitor is denied access to phone beacause he/she didn't pay $1. */
      j=0;
      talkingTime=0;
      /* printf("Visitor%d \t  UNAVAILABLE \t %d/%d units \t %d \t   NOTAPPLICABLE    DENIED \t   Money paid is $0 - verified by operator 
	  %d \n",who+1,j,talkingTime,operatorToUse+1,checkCorrectOperatorV+1); */
	  /*	   AcquireLock(displayLock); */
	  Write("Visitor ",8,1);
	   num = who+1;
		itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
		Write(" \t UNAVAILABLE \t",100,1);	   
		num = j;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("/",1,1);
	    num=talkingTime;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" units \t ",10,1);
	    num=operatorToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t",6,1);	
	    Write(" NOTAPPLICABLE    DENIED \t   Money paid is $0 - verified by operator ",100,1);
	    num=checkCorrectOperatorV+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \n",3,1);
		/*ReleaseLock(displayLock);*/
	Yield();

      /* printf("Access to Phone for visitor %d Denied by Operator %d!\n",who+1,operatorToUse+1); */
    }
  else if (thisActivate==1) /* visitor has paid $1. Operator verifies and visitor is allowed to make a call */
    {
      /* Now Talk */
      talkingTime = RandomFunction(5); /* randomly generate the amount of time the visitor will talk on the phone */
      /* loop for the visitor to talk on the phone for the randomly generated time period */
      for (i=1;i<=talkingTime;i++){
	/* printf("Visitor%d \t  %d \t\t %d/%d units \t %d \t   NOTAPPLICABLE    ACCEPTED \t   
	Money paid is $1 - verified by operator %d \n",who+1,phoneToUse+1,i,talkingTime,operatorToUse+1,checkCorrectOperatorV+1); */
	/*AcquireLock(displayLock);*/
	Write("Visitor ",8,1);
	   num = who+1;
		itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
		Write(" \t",2,1);
	    num = phoneToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("\t\t ",5,1);
		num = i;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write("/",1,1);
	    num=talkingTime;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" units \t ",10,1);
	    num=operatorToUse+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \t",6,1);	
	    Write(" NOTAPPLICABLE    ACCEPTED \t   Money paid is $1 - verified by operator ",100,1);
	    num=checkCorrectOperatorV+1;
	    itoa(printing,10,num);
	    Write(printing,sizeof(printing),1);
	    Write(" \n",3,1);
		/*ReleaseLock(displayLock);*/
	/*Yield();*/
      }
      /* visitor is done talking */
      /* Set the phone status to be free */
    }
  AcquireLock(lockID1);
  SetSharedInt(phoneStatus,phoneToUse,FREE);
  if(GetSharedInt(presidentStatus,0)==0) /* president is not waking to talk */
    {
      if(CheckCondWaitQueue(condID2))
		SignalCV(condID2,lockID1); /* wake up the next senator waiting to talk */
      else
		SignalCV(condID3,lockID1); /* if no senator is waiting, then wake up the next visitor waiting to talk */
    }
  else /* president is waiting to talk, so senators and visitors will have to wait */
    {
      callPresident = TRUE;
	  /*
      for(i=0;i<NOOFPHONES;i++)
		if((i!=phoneToUse)&&(GetSharedInt(phoneStatus,i)==BUSY)) // check if even a single phone is busy other than the phone just used by the visitor which he/she sets to free 
	  {
	    callPresident = FALSE;
	    break;
	  }*/
		i = ArraySearch(phoneStatus, phoneToUse, BUSY);
		if(i!=NOOFPHONES)
			callPresident = FALSE;
      if(callPresident==TRUE)
	SignalCV(condID1,lockID1); /* if all phones are free, then no one is talking currently and so, signal the president */
    }
  /* visitor goes away and does not return. Remember visitors can make a maximum of just one call       */
  ReleaseLock(lockID1);	
  WriteMe("Visitor ");WriteNum(who + 1);WriteMe("Leaving\n");
  Exit(0);
}
Example #22
0
int main() {
	/* ------------------Local data -------------------------*/
	int myIndex;

	int initIndex = CreateMV("PicIndex", sizeof("PicIndex"), 1, 0x9999);
	int initIndexLock = ServerCreateLock("PicIndexLock", sizeof("PicIndexLock"), 1);

	int mySSN;
	int i;
	int cType = 0;

	enum BOOLEAN loop = true;
	int shutdown = CreateMV("shutdown", sizeof("shutdown"), 1, 0x9999);
	/* -----------------Shared Data------------------------*/

	/* Number of customers/senators in office and thier locks */
	int officeSenator = CreateMV("officeSenator", sizeof("officeSenator"), 1, 0x9999);
	int officeCustomer = CreateMV("officeCustomer", sizeof("officeCustomer"), 1, 0x9999);	
	int senatorLock = ServerCreateLock("senatorLock", sizeof("senatorLock"), 1);
	int customerLock = ServerCreateLock("customerLock", sizeof("customerLock"), 1);

	/*Locks, conditions, and data used for waitinng */
	int clerkWaitLock = ServerCreateLock("clerkWaitLock", sizeof("clerkWaitLock"), 1);
	int clerkWaitCV = ServerCreateCV("clerkWaitCV", sizeof("clerkWaitCV"), 1);
	int numPicWait = CreateMV("numPicWait", sizeof("numPicWait"), 1, 0x9999);

	/* Reg and priv line lengths, line locks, and reg and priv line conditions. */
	int regPCLineLength = CreateMV("regPCLineLength", sizeof("regPCLineLength"), 1, 0x9999);
	int privPCLineLength = CreateMV("privPCLineLength", sizeof("privPCLineLength"), 1, 0x9999);
	int acpcLineLock = ServerCreateLock("acpcLineLock", sizeof("acpcLineLock"), 1);
	int regPCLineCV = ServerCreateCV("regPCLineCV", sizeof("regPCLineCV"), 1);
	int privPCLineCV = ServerCreateCV("privPCLineCV", sizeof("privPCLineCV"), 1);


	/* Individual clerk locks, conditions, data, data booleans, and states */
	int picLock = ServerCreateLock("picLock", sizeof("picLock"), NUM_CLERKS);
	int picCV = ServerCreateCV("picCV", sizeof("picCV"), NUM_CLERKS);
	int picDataBool = CreateMV("picDataBool", sizeof("picDataBool"), NUM_CLERKS, 0x9999);
	int picState = CreateMV("picState", sizeof("picState"), NUM_CLERKS, 0x9999);
	int picData = CreateMV("picData", sizeof("picData"), NUM_CLERKS, 0x9999);

	/* Money data and locks for each clerk type */
	int picMoney = CreateMV("picMoney", sizeof("picMoney"), 1, 0x9999);
	int picMoneyLock = ServerCreateLock("picMoneyLock", sizeof("picMoneyLock"), 1);

	/* Individual customer's file state, type, and its lock */
	int fileLock = ServerCreateLock("fileLock", sizeof("fileLock"), NUM_CUSTOMERS + NUM_SENATORS);
	int fileState = CreateMV("fileState", sizeof("fileState"), NUM_CUSTOMERS + NUM_SENATORS, 0x9999);
	int fileType = CreateMV("fileType", sizeof("fileType"), NUM_CUSTOMERS + NUM_SENATORS, 0x9999);

	traceLock = ServerCreateLock("traceLock", sizeof("traceLock"), 1);
	
	/* initializes myIndex */
	ServerAcquire(initIndexLock, 0);
	myIndex = GetMV(initIndex, 0);
	SetMV(initIndex, 0, GetMV(initIndex, 0) + 1);
	ServerRelease(initIndexLock, 0);
	
	SetMV(picState, myIndex, 1);

	/* --------------------BEGIN PICCLERK STUFF----------------*/
	while(loop == true){
		if (GetMV(shutdown, 0) == 1) {
			ServerAcquire(traceLock, 0);
			ClerkTrace("Pic", myIndex, 0x00, 0, "Shutting down.\n");
			ServerRelease(traceLock, 0);
			Exit(0);
		}
		ServerAcquire(senatorLock, 0);
		ServerAcquire(customerLock, 0);
		if (GetMV(officeSenator, 0) > 0 && GetMV(officeCustomer, 0) > 0) {
			ServerRelease(senatorLock, 0);
			ServerRelease(customerLock, 0);
			
			ServerAcquire(clerkWaitLock, 0);
			ServerWait(clerkWaitCV, 0, clerkWaitLock, 0);
			ServerRelease(clerkWaitLock, 0);
		}
		else{
			ServerRelease(senatorLock, 0);
			ServerRelease(customerLock, 0);
		}

		ServerAcquire(acpcLineLock, 0);

		/* Check for the privileged customer line first
		* If there are privileged customers, do PicClerk tasks, then receive $500
		*/
		if(GetMV(privPCLineLength, 0) > 0){
			SetMV(privPCLineLength, 0, GetMV(privPCLineLength, 0)-1);
			
			ServerAcquire(senatorLock, 0);
			SetMV(numPicWait, 0, GetMV(numPicWait, 0)+1);		/* Shows customer that one clerk is waiting */
			ServerRelease(senatorLock, 0);

			ServerAcquire(picLock, myIndex);
			SetMV(picState, myIndex, 0); /* 0 = AVAILABLE */
			ServerSignal(privPCLineCV, 0, acpcLineLock, 0);
			ServerRelease(acpcLineLock, 0);
			
			ServerWait(picCV, myIndex, picLock, myIndex);	/* Waits for the next customer */

			mySSN = GetMV(picData, myIndex);
			/* check the customer type */
			ServerAcquire(fileLock, mySSN);
			if (GetMV(fileType, mySSN) == 0) { /* 0 = CUSTOMER */
				cType = 0;
			} else {
				cType = 1;	/* 1 = SENATOR */
			}

			if(GetMV(fileState, mySSN) == 0){	/* 0 = NONE */
				SetMV(fileState, mySSN, 1);/* 1 = PICDONE */
				ServerRelease(fileLock, mySSN);
			}
			else if(GetMV(fileState, mySSN) == 2 ){ /* 2 = APPDONE */
				SetMV(fileState, mySSN, 3); /* 3 = APPPICDONE */
				ServerRelease(fileLock, mySSN);
			}
			else{
				ServerAcquire(traceLock, 0);
				ClerkTrace("Pic", myIndex, "Cust", mySSN,
					"ERROR: Customer does not have either an application or no application. What are you doing here?\n");
				ServerRelease(traceLock, 0);
				ServerRelease(fileLock, mySSN);
			}

			ServerAcquire(traceLock, 0);
			if (cType == 0) {
				ClerkTrace("Pic", myIndex, "Cust", mySSN, "Takes picture of Customer.\n");
			} else {
				ClerkTrace("Pic", myIndex, "Sen", mySSN, "Takes picture of Senator.\n");
			}
			ServerRelease(traceLock, 0);

			/* yield to take picture
			* print statement: "Taking picture"
			* picCV->Signal then picCV->Wait to
			* show customer picture
			*/
			while(GetMV(picDataBool, myIndex) == 0){ /* 0 = false */
				for(i = 0; i < 4; i++){
					Yield();
				}
				ServerSignal(picCV, myIndex, picLock, myIndex);	
				ServerWait(picCV, myIndex, picLock, myIndex);	/* Shows the customer the picture */

				if(GetMV(picDataBool, myIndex) == 0){
					ServerAcquire(traceLock, 0);
					if (cType == 0) {
						ClerkTrace("Pic", myIndex, "Cust", mySSN, "Takes picture of Customer again.\n");

					} else {
						ClerkTrace("Pic", myIndex, "Sen", mySSN, "Takes picture of Senator again.\n");
					}
					ServerRelease(traceLock, 0);
				}
			}


			/* file picture using
			* current thread yield
			
			for(i = 0; i < 20; i++){
				Yield();
			}*/
			ServerAcquire(traceLock, 0);
			if (cType == 0) {
				ClerkTrace("Pic", myIndex, "Cust", mySSN, "Informs Customer that the picture has been completed.\n");
			} else {
				ClerkTrace("Pic", myIndex, "Sen", mySSN, "Informs Senator that the picture has been completed.\n");
			}
			ServerRelease(traceLock, 0);

			/* signal customer awake */
			ServerAcquire(picMoneyLock, 0);
			SetMV(picMoney, 0, GetMV(picMoney, 0) + 500);

			ServerAcquire(traceLock, 0);
			if (cType == 0) {
				ClerkTrace("Pic", myIndex, "Cust", mySSN, "Accepts $500 from Customer.\n");
			} else {
				ClerkTrace("Pic", myIndex, "Cust", mySSN, "Accepts $500 from Senator.\n");
			}
			ServerRelease(traceLock, 0);

			ServerRelease(picMoneyLock, 0);

			SetMV(picDataBool, myIndex, 0);
			ServerSignal(picCV, myIndex, picLock, myIndex); /* signal customer awake */
			ServerRelease(picLock, myIndex); /* release clerk lock */
		}
		/* Check for regular customer line next
		* If there are regular customers, do PicClerk tasks
		*/
		else if(GetMV(regPCLineLength,0) > 0){
			SetMV(regPCLineLength, 0, GetMV(regPCLineLength, 0)-1);

			ServerAcquire(senatorLock, 0);
			SetMV(numPicWait, 0, GetMV(numPicWait, 0)+1);	/* shows customer that one clerk is waiting */
			ServerRelease(senatorLock, 0);

			ServerAcquire(picLock, myIndex);
			SetMV(picState, myIndex, 0); /* 0  = AVAILABLE */
			ServerSignal(regPCLineCV, 0, acpcLineLock, 0);
			ServerRelease(acpcLineLock, 0);
			
			ServerWait(picCV, myIndex, picLock, myIndex);	/* Waits for the next customer */

			mySSN = GetMV(picData, myIndex);
			/* check the customer type */
			ServerAcquire(fileLock, mySSN);
			if (GetMV(fileType, mySSN) == 0) {
				cType = 0;
			} else {
				cType = 1;
			}

			if(GetMV(fileState, mySSN) == 0){	/* 0 = NONE */
				SetMV(fileState, mySSN, 1);/* 1 = PICDONE */
				ServerRelease(fileLock, mySSN);
			}
			else if(GetMV(fileState, mySSN) == 2 ){ /* 2 = APPDONE */
				SetMV(fileState, mySSN, 3); /* 3 = APPPICDONE */
				ServerRelease(fileLock, mySSN);
			}
			else{
				ServerAcquire(traceLock, 0);
				ClerkTrace("Pic", myIndex, "Cust", mySSN,
					"ERROR: Customer does not have either an application or no application. What are you doing here?\n");
				ServerRelease(traceLock, 0);
				ServerRelease(fileLock, mySSN);
			}

			ServerAcquire(traceLock, 0);
			if (cType == 0) {
				ClerkTrace("Pic", myIndex, "Cust", mySSN, "Takes picture of Customer.\n");
			} else {
				ClerkTrace("Pic", myIndex, "Sen", mySSN, "Takes picture of Senator.\n");
			}
			ServerRelease(traceLock, 0);
			
				/* yield to take picture
				* print statement: "Taking picture"
				* picCV->Signal then picCV->Wait to
				* show customer picture
				*/
			while(GetMV(picDataBool, myIndex) == 0){
				for(i = 0; i < 4; i++){
					Yield();
				}
				ServerSignal(picCV, myIndex, picLock, myIndex);	
				ServerWait(picCV, myIndex, picLock, myIndex);	/* Shows the customer the picture */

				if(GetMV(picDataBool, myIndex) == 0){
					ServerAcquire(traceLock, 0);
					if (cType == 0) {
						ClerkTrace("Pic", myIndex, "Cust", mySSN, "Takes picture of Customer again.\n");
					} else {
						ClerkTrace("Pic", myIndex, "Sen", mySSN, "Takes picture of Senator again.\n");
					}
					ServerRelease(traceLock, 0);
				}
			}


			/* file picture using
			* current thread yield
			
			for(i = 0; i < 20; i++){
				Yield();
			}*/
			ServerAcquire(traceLock, 0);
			if (cType == 0) {
				ClerkTrace("Pic", myIndex, "Cust", mySSN, "Informs Customer that the picture has been completed.\n");
			} else {
				ClerkTrace("Pic", myIndex, "Sen", mySSN, "Informs Senator that the picture has been completed.\n");
			}
			ServerRelease(traceLock, 0);

			SetMV(picDataBool, myIndex, 0);
			ServerSignal(picCV, myIndex, picLock, myIndex); /* signal customer awake */
			ServerRelease(picLock, myIndex); /* release clerk lock */
		}		
		/* If there are neither privileged or regular customers, go on break */
		else{
			ServerRelease(acpcLineLock, 0);
			ServerAcquire(picLock, myIndex);
			SetMV(picState, myIndex, 2); /* 2 = BREAK */
			
			ServerAcquire(traceLock, 0);
			ClerkTrace("Pic", myIndex, 0x00, 0, "Going on break.\n");
			ServerRelease(traceLock, 0);

			ServerWait(picCV, myIndex, picLock, myIndex);
			
			ServerAcquire(traceLock, 0);
			ClerkTrace("Pic", myIndex, 0x00, 0, "Returning from break.\n");
			ServerRelease(traceLock, 0);
			
			ServerRelease(picLock, myIndex);
		}
	}
}
Example #23
0
BOOL
TWIN_DriverMessage(LPMSG lpMsg, HWND hWnd,
	      UINT uMin, UINT uMax,UINT uFlg,BOOL bNoWait)
{
    DWORD   dwerv;
    HANDLE  hTask;
    LPQUEUE lpQueue;

    if (hWnd && !IsWindow(hWnd))
	hWnd = 0;

    if (hWnd)
	hTask = GetWindowTask(hWnd);
    else
	hTask = GetCurrentTask();
    lpQueue = QueueGetPtr(hTask);

    /******************************************/
    /* what is this?  it is not called...     */
    /*hFocusTask = GetWindowTask(GetFocus()); */
    /******************************************/

  lpMsg->hwnd = 0;
  labLoop:
    while(1) {
	while (lpSendMessageStack && 
	       lpSendMessageStack->hReceivingTask == GetCurrentTask() &&
	       !lpSendMessageStack->bSendReceived)
	{
	    TWIN_ReceiveMessage(FALSE);
	}

	/* try for a message from application queue */
	if (QueueGetMsg(lpQueue, lpMsg, hWnd, uMin, uMax, uFlg)) {
	    break;
	}

	/* try for a message from system queue */
	if (QueueGetMsg(0,lpMsg,hWnd,uMin,uMax,uFlg)) {
	    break;
	}

	if (uMin <= WM_PAINT && (!uMax || uMax >= WM_PAINT)) {
	    /* finally, check if the window needs a paint message */
	    if(lpQueue->wQueueFlags & QFPAINT) {
	      labTryNext:
		if((lpMsg->hwnd = InternalUpdateWindows())) {
		    if (TestWF(lpMsg->hwnd, WFNCDIRTY)) {
			if (NonEmptyNCRect(lpMsg->hwnd)) {
			    lpMsg->message = WM_NCPAINT;
			    lpMsg->wParam = 0;
			    lpMsg->lParam = 0L;
			    break;
			}
			else {
			    ClearWF(lpMsg->hwnd, WFNCDIRTY);
			}
		    }
		    if (TestWF(lpMsg->hwnd, WFDIRTY)) {
			if (IsIconic(lpMsg->hwnd) && 
			    GetClassIcon(lpMsg->hwnd)) {
			    lpMsg->message = WM_PAINTICON;
			    lpMsg->wParam = 1;
			}
			else {
			    lpMsg->message = WM_PAINT;
			    lpMsg->wParam = 0;
			}
			lpMsg->lParam = 0L;
			break;
		    }
		    else
			goto labTryNext;
		}
		lpQueue->wQueueFlags &= ~QFPAINT;
	    }
	}

	if ((uMin <= WM_TIMER && (!uMax || uMax >= WM_TIMER)) ||
	    (uMin <= WM_SYSTIMER && (!uMax || uMax >= WM_SYSTIMER))) {
	    if(lpQueue->wQueueFlags & QFTIMER) {
		if (TWIN_GetTimerMsg(hWnd,hTask,lpMsg,uFlg)) {
		    break;
		}
	    }
	}

	/* none of the above, so see if system is ready. */
	if (!TWIN_InDriverWait)
	{

	    TWIN_InDriverWait = TRUE;
	    dwerv = DriverWaitEvent(TRUE);
	    TWIN_InDriverWait = FALSE;

	    if (!dwerv && !bNoWait)
	    {
		/*
		 *  The code here used to call ReadyTask(GetCurrentTask())
		 *  before calling InternalYield(), but that results in
		 *  a solid-run condition if more than one task is
		 *  defined, because it results in the other task looking
		 *  like it's ready to run, when all tasks should be waiting
		 *  on a driver event.  So we yield if necessary, but do
		 *  not set ourselves as ready-to-run if we do.  We will
		 *  be run again when we first get a message in our queue.
		 */
#if defined(MAC_TASKING_PATCH)
		ReadyTask(GetCurrentTask());
#endif
		if (!InternalYield())
		{
		    TWIN_InDriverWait = TRUE;
		    (void)DriverWaitEvent(FALSE);
		    TWIN_InDriverWait = FALSE;
		}
	    }
	    else if (!(uFlg & PM_NOYIELD))
		Yield();
	}
	else if (!(uFlg & PM_NOYIELD))
	    InternalYield();

	if(bNoWait)
	    return FALSE;
    }
    if (CallGetMessageHooks(lpMsg,uFlg & PM_REMOVE))
	goto labLoop;
    return TRUE;
}
inline void yield()
{
    Yield();
}
Example #25
0
//----------------------------------------------------------------------
//
//	doInterrupt
//
//	Handle an interrupt or trap.
//
//----------------------------------------------------------------------
void
dointerrupt (unsigned int cause, unsigned int iar, unsigned int isr,
	     uint32 *trapArgs)
{
  int	result;
  int	i;
  uint32	args[4];
  int	intrs;
  uint32 handle;
  int ihandle;

  dbprintf ('t',"Interrupt cause=0x%x iar=0x%x isr=0x%x args=0x%08x.\n",
	    cause, iar, isr, trapArgs);
  // If the TRAP_INSTR bit is set, this was from a trap instruction.
  // If the bit isn't set, this was a system interrupt.
  if (cause & TRAP_TRAP_INSTR) {
    cause &= ~TRAP_TRAP_INSTR;
    switch (cause) {
    case TRAP_CONTEXT_SWITCH:
      dbprintf ('t', "Got a context switch trap!\n");
      ProcessSchedule ();
      break;
    case TRAP_EXIT:
      dbprintf ('t', "Got an exit trap!\n");
      ProcessDestroy (currentPCB);
      ProcessSchedule ();
      break;
    case TRAP_PROCESS_FORK:
      dbprintf ('t', "Got a fork trap!\n");
      break;
    case TRAP_PROCESS_SLEEP:
      dbprintf ('t', "Got a process sleep trap!\n");
      ProcessSuspend (currentPCB);
      ProcessSchedule ();
      break;
    case TRAP_PRINTF:
      // Call the trap printf handler and pass the arguments and a flag
      // indicating whether the trap was called from system mode.
      dbprintf ('t', "Got a printf trap!\n");
      TrapPrintfHandler (trapArgs, isr & DLX_STATUS_SYSMODE);
      break;
    case TRAP_OPEN:
      // Get the arguments to the trap handler.  If this is a user mode trap,
      // copy them from user space.
      if (isr & DLX_STATUS_SYSMODE) {
	args[0] = trapArgs[0];
	args[1] = trapArgs[1];
      } else {
	char	filename[32];
	// trapArgs points to the trap arguments in user space.  There are
	// two of them, so copy them to to system space.  The first argument
	// is a string, so it has to be copied to system space and the
	// argument replaced with a pointer to the string in system space.
	MemoryCopyUserToSystem (currentPCB, trapArgs, args, sizeof(args[0])*2);
	MemoryCopyUserToSystem (currentPCB, args[0], filename, 31);
	// Null-terminate the string in case it's longer than 31 characters.
	filename[31] = '\0';
	// Set the argument to be the filename
	args[0] = (uint32)filename;
      }
      // Allow Open() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, args[1] + 0x10000);
      printf ("Got an open with parameters ('%s',0x%x)\n", args[0], args[1]);
      RestoreIntrs (intrs);
      break;
    case TRAP_CLOSE:
      // Allow Close() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_READ:
      // Allow Read() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_WRITE:
      // Allow Write() calls to be interruptible!
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_DELETE:
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_SEEK:
      intrs = EnableIntrs ();
      ProcessSetResult (currentPCB, -1);
      RestoreIntrs (intrs);
      break;
    case TRAP_PROCESS_CREATE:
      TrapProcessCreateHandler(trapArgs, isr & DLX_STATUS_SYSMODE);
      break;
    case TRAP_PROCESS_YIELD:
      Yield();
      //ProcessSetResult(currentPCB, -1);
      break;
    case TRAP_SHARE_CREATE_PAGE:
      handle = MemoryCreateSharedPage(currentPCB);
      ProcessSetResult(currentPCB, handle);
      break;
    case TRAP_SHARE_MAP_PAGE:
      handle = GetUintFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      handle = (uint32)mmap(currentPCB, handle);
      ProcessSetResult(currentPCB, handle);
      break;
    case TRAP_SEM_CREATE:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      ihandle = SemCreate(ihandle);
      ProcessSetResult(currentPCB, ihandle); //Return handle
      break;
    case TRAP_SEM_WAIT:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      handle = SemHandleWait(ihandle);
      ProcessSetResult(currentPCB, handle); //Return 1 or 0
      break;
    case TRAP_SEM_SIGNAL:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      handle = SemHandleSignal(ihandle);
      ProcessSetResult(currentPCB, handle); //Return 1 or 0
      break;
    case TRAP_LOCK_CREATE:
      ihandle = LockCreate();
      ProcessSetResult(currentPCB, ihandle); //Return handle
      break;
    case TRAP_LOCK_ACQUIRE:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      handle = LockHandleAcquire(ihandle);
      ProcessSetResult(currentPCB, handle); //Return 1 or 0
      break;
    case TRAP_LOCK_RELEASE:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      handle = LockHandleRelease(ihandle);
      ProcessSetResult(currentPCB, handle); //Return 1 or 0
      break;
    case TRAP_COND_CREATE:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      ihandle = CondCreate(ihandle);
      ProcessSetResult(currentPCB, ihandle); //Return handle
      break;
    case TRAP_COND_WAIT:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      ihandle = CondHandleWait(ihandle);
      ProcessSetResult(currentPCB, ihandle); //Return 1 or 0
      break;
    case TRAP_COND_SIGNAL:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      ihandle = CondHandleSignal(ihandle);
      ProcessSetResult(currentPCB, ihandle); //Return 1 or 0
      break;
    case TRAP_TIMERGET:
      ihandle = TimerGet();
      ProcessSetResult(currentPCB,ihandle);
      break;
    case TRAP_COND_BROADCAST:
      ihandle = GetIntFromTrapArg(trapArgs, isr & DLX_STATUS_SYSMODE);
      ihandle = CondHandleBroadcast(ihandle);
      ProcessSetResult(currentPCB, ihandle); //Return 1 or 0
      break;
    default:
      printf ("Got an unrecognized trap (0x%x) - exiting!\n",
	      cause);
      exitsim ();
      break;
    }
  } else {
    switch (cause) {
    case TRAP_TIMER:
      dbprintf ('t', "Got a timer interrupt!\n");
      ProcessSchedule ();
      break;
    case TRAP_KBD:
      do {
	i = *((uint32 *)DLX_KBD_NCHARSIN);
	result = *((uint32 *)DLX_KBD_GETCHAR);
	printf ("Got a keyboard interrupt (char=0x%x(%c), nleft=%d)!\n",
		result, result, i);
      } while (i > 1);
      break;
    case TRAP_ACCESS:
      printf ("Exiting after illegal access at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    case TRAP_ADDRESS:
      printf ("Exiting after illegal address at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    case TRAP_ILLEGALINST:
      printf ("Exiting after illegal instruction at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    case TRAP_PAGEFAULT:
      printf ("Exiting after page fault at iar=0x%x, isr=0x%x\n",
	      iar, isr);
      exitsim ();
      break;
    default:
      printf ("Got an unrecognized system interrupt (0x%x) - exiting!\n",
	      cause);
      exitsim ();
      break;
    }
  }
  dbprintf ('t',"About to return from dointerrupt.\n");
  // Note that this return may schedule a new process!
  intrreturn ();
}
Example #26
0
static void doCashierClerk(int* index, int* cashDollars)
{	
	int myClerk, x, rando;
	
	while(TRUE)
	{	
		
		myClerk = -1;
		tprintf("Senator [%d]: Going to the CashClerk\n",*index,0,0,"","");	
		/*cashLineLock->Acquire();	*/
		Acquire(cashLineLock);
		
		regCashLineLength++;
		tprintf("Senator [%d]: Waiting in the Regular Line for next available CashClerk\n",*index,0,0,"","");
		/*regCashLineCV->Wait(cashLineLock);	*/
		Wait(regCashLineCV, cashLineLock);		
				
		tprintf("Senator[%d]: Finding available CashClerk...\n",*index,0,0,"","");
		for(x = 0; x < MAX_CASH_CLERKS; x++)
		{				
			if(cashClerkStatuses[x] == CLERK_AVAILABLE)
			{
				myClerk = x;					
				tprintf("Senator [%d]: Going to chill with CashClerk[%d]\n",*index,myClerk,0,"","");					
				cashClerkStatuses[myClerk] = CLERK_BUSY;					
				break;				
			}
			else
				tprintf("Senator [%d]: CashClerk[%d] is unavailable\n",*index,x,0,"","");

		}	
		
		if (myClerk == -1) {
			printf("Senator [%d]: Woke up with a CashClerk index of -1, halting the machine for now.",*index,0,0,"","");
			Halt();
		}

		/*cashClerkLocks[myClerk]->Acquire();
		cashLineLock->Release();		*/
		Acquire(cashClerkLocks[myClerk]);
		Release(cashLineLock);
							
		cashClerkSSNs[myClerk] = *index;			
		printf("Senator [%d] goes to CashClerk[%d]\n",*index,myClerk,0,"","");			
		/*interact with clerk			*/
		/*cashClerkCVs[myClerk]->Signal(cashClerkLocks[myClerk]);
		cashClerkCVs[myClerk]->Wait(cashClerkLocks[myClerk]);*/
		Signal(cashClerkCVs[myClerk], cashClerkLocks[myClerk]);
		Wait(cashClerkCVs[myClerk], cashClerkLocks[myClerk]);
		
		/*pay for passport. If it's not processed, get back in line*/
		if(!cashPunish[myClerk])
		{				
			printf("Senator [%d] gets [valid] certification by Cashier[%d]\n",*index,myClerk,0,"","");
			printf("Senator [%d] pays $100 to Cashier[%d] for their passport\n",*index,myClerk,0,"","");
			cashClerkMoney[myClerk] += 100;				
			*cashDollars-=100;
			/*cashClerkCVs[myClerk]->Signal(cashClerkLocks[myClerk]);
			cashClerkCVs[myClerk]->Wait(cashClerkLocks[myClerk]);*/
			Signal(cashClerkCVs[myClerk], cashClerkLocks[myClerk]);
			Wait(cashClerkCVs[myClerk], cashClerkLocks[myClerk]);
			
			tprintf("Senator [%d]: Passport paid for like a pro. CashDollars = [$%d]\n", *index, *cashDollars,0,"","");											
			/*cashClerkLocks[myClerk]->Release();*/
			Release(cashClerkLocks[myClerk]);
			
			printf("Senator [%d] leaves the passport office...\n",*index,0,0,"","");
			/*customerOfficeLock->Acquire();*/
			Acquire(entryLock);
			senatorsInOffice--;
			/*customerOfficeLock->Release();*/
			Release(entryLock);
			break;				
		}
		/*cashClerkLocks[myClerk]->Release();*/
		Release(cashClerkLocks[myClerk]);
		printf("Senator [%d] gets [invalid] certification by Cashier[%d]\n",*index,myClerk,0,"","");
		printf("Senator [%d] is punished to wait by Cashier[%d]\n",*index,myClerk,0,"","");
		tprintf("Senator [%d]: NOT READY!? Going back to the end of the line...\n",*index,0,0,"","");
		rando = Rand()%80+20;					
		for(x = 0; x < rando; x++)
			Yield();																				
	}
}
Example #27
0
/*
 * Wrapper for Yield
 * */
void YIELD()
{
	Yield();
}
Example #28
0
static void doPassPortClerk(int *index, int* cashDollars){	

	bool privLined = FALSE;
	bool bribed = FALSE;
	int myClerk, x, rando;

	while(TRUE)
	{	
	
		myClerk = -1;
		tprintf("Senator [%d]: Going to the PassportClerk\n",*index,0,0,"","");
		tprintf("Senator [%d]: Acquiring PassLineLock...\n",*index,0,0,"","");		
		/*passLineLock->Acquire();*/
		Acquire(passLineLock);
		printf("Senator [%d]: What line should I choose for the PassportClerk?\n",*index,0,0,"","");
		/*check for senator*/
		if(*cashDollars > 100 || privLined) /*get in a privledged line*/
		{								
			privLined = TRUE;				
			tprintf("Senator [%d]: Priveleged line, baby. CashDollars = $%d\n",*index,*cashDollars,0,"","");
			privPassLineLength++;
			tprintf("Senator [%d]: Waiting in the Priveledged Line for next available PassportClerk\n",*index,0,0,"","");
			/*privPassLineCV->Wait(passLineLock);*/
			Wait(privPassLineCV, passLineLock);			
		}
		else /*get in a normal line*/
		{
			tprintf("Senator [%d]: Regular line, suckas. CashDollars = $%d\n",*index,*cashDollars,0,"","");
			regPassLineLength++;
			tprintf("Senator [%d]: Waiting in the Regular Line for next available PassportClerk\n",*index,0,0,"","");
			/*regPassLineCV->Wait(passLineLock);		*/
			Wait(regPassLineCV, passLineLock);	
		}
		tprintf("Senator [%d]: Finding available PassClerk...\n",*index,0,0,"","");
		for(x = 0; x < MAX_PASS_CLERKS; x++)
		{				
			if(passClerkStatuses[x] == CLERK_AVAILABLE)
			{
				myClerk = x;					
				tprintf("Senator [%d]: Going to chill with PassClerk[%d]\n",*index,myClerk,0,"","");					
				passClerkStatuses[myClerk] = CLERK_BUSY;					
				break;				
			}
			else
				tprintf("Senator [%d]: PassClerk[%d] is unavailable\n",*index,x,0,"","");

		}

		if (myClerk == -1) {
			printf("Senator [%d]: Woke up with a PassClerk index of -1, halting the machine for now.",*index,0,0,"","");
			Halt();
		}
		
		/*passClerkLocks[myClerk]->Acquire();*/
		Acquire(passClerkLocks[myClerk]);
		/*passLineLock->Release();	*/
		Release(passLineLock);						
		passClerkSSNs[myClerk] = *index;
		if(privLined && !bribed)
		{
			bribed = TRUE;
			printf("Senator [%d] is willing to pay $500 to PassportClerk[%d] for moving ahead in line\n",*index,myClerk,0,"","");
			passClerkMoney[myClerk] += 500;
			passClerkBribed[myClerk] = TRUE;
			*cashDollars -= 500;
		}
		printf("Senator [%d] goes to PassportClerk[%d]\n",*index,myClerk,0,"","");
		/*interact with clerk		*/	
		/*passClerkCVs[myClerk]->Signal(passClerkLocks[myClerk]);
		passClerkCVs[myClerk]->Wait(passClerkLocks[myClerk]);*/
		Signal(passClerkCVs[myClerk], passClerkLocks[myClerk]);
		Wait(passClerkCVs[myClerk], passClerkLocks[myClerk]);
		/*get passport from clerk, if not ready, go to the back of the line?*/
		if(!passPunish[myClerk])
		{
			printf("Senator [%d] is [certified] by PassportClerk[%d]\n",*index,myClerk,0,"","");
			tprintf("Senator [%d]: Passport. GET!.\n", *index,0,0,"","");						
			tprintf("Senator [%d]: Done and done.\n",*index,0,0,"","");
			/*passClerkLocks[myClerk]->Release();*/
			Release(passClerkLocks[myClerk]);
			tprintf("Senator [%d]: Going to next clerk...\n",*index,0,0,"","");
			break;				
		}
		/*passClerkLocks[myClerk]->Release();*/
		Release(passClerkLocks[myClerk]);
		printf("Senator [%d] is [not certified] by PassportClerk[%d]\n",*index,myClerk,0,"","");
		printf("Senator [%d] is being forced to wait by PassportClerk[%d]\n",*index,myClerk,0,"","");
		rando = Rand()%80+20;					
		for(x = 0; x < rando; x++)
			Yield();															
	}

}
/* %%Function:YieldPR %%Owner:BRADV */
NATIVE BOOL YieldPR() /* WINIGNORE - PROFILE only */
{
	return Yield();
}
int main()
{
	Yield();
    /* not reached */
}