Esempio n. 1
0
void linkedQueueType<Type>::copyQueue(const linkedQueueType<Type>& otherQueue){
    nodeType<Type> *newNode;
    nodeType<Type> *current;
    
    if(!otherQueue.front()){
        std::cout << "Cannot copy an empty queue" << std::endl;
        initializeQueue();
        return;
    }
    
    if (queueFront != NULL){
        deleteQueue();
    }
    initializeQueue();
    current = otherQueue.queueFront;
    queueFront = new nodeType<Type>;
    queueFront->info = current->info;
    queueFront->link = NULL;
    queueRear = queueFront;
    current = current->link;
    
    while(current != NULL){
        newNode = new nodeType<Type>;
        newNode->info = current->info;
        newNode->link = NULL;
        queueRear->link = newNode;
        queueRear = newNode;
        current = current->link;
    }
}
Esempio n. 2
0
// Updates the dispatcher
// @par: PCB pointer    process PCB
// @ret: none
void enqueueToPriority(PCB *process) {
    int p = process->priority;

    if (p == 0) {
        if (!realTimeQueue) {
            realTimeQueue = initializeQueue();
        }
        enqueueProcess(realTimeQueue, process);
    } else if (p == 1) {
        if (!p1Queue) {
            p1Queue = initializeQueue();
        }
        enqueueProcess(p1Queue, process);
    } else if (p == 2) {
        if (!p2Queue) {
            p2Queue = initializeQueue();
        }
        enqueueProcess(p2Queue, process);
    } else {
        if (!p3Queue) {
            p3Queue = initializeQueue();
        }
        enqueueProcess(p3Queue, process);
    }
}
int evaluate(ParseTreeNode *p_root){
    ParseTreeNode *result_node;
    int val;

    initializeStack();
    initializeQueue(); /* So that the tree will not be changed */

    postOrderTraversal(p_root, &evaluatorHelper);

    result_node = pop();
    val = *(result_node->m_token->m_data_container->m_int);

    /* Free the resources */
    while(!isQueueEmpty()){
        result_node = dequeue();

        free(result_node->m_token->m_data_container);
        result_node->m_token->m_data_container = NULL;

        free(result_node->m_token);
        result_node->m_token = NULL;

        free(result_node);
        result_node = NULL;
    }

    return val;
}
Esempio n. 4
0
/************************************************************************************
*
*	createAndInitializeQueue
*
*	Creates and initializes data for our queue
*      
*	Arguments:
*
*      unsigned short elements - the number of elements for our queue
*      char growOnDemand - Tells us whether or not the queue should grow if the capacity is reached
*
*	Return Value:
*
*		The initialized queue
*
*************************************************************************************/
Queue createAndInitializeQueue(unsigned short elements,char growOnDemand)
{
  Queue newQueue;

  // allocate memory for our queue
  newQueue = malloc (sizeof(struct QueueDataPacket));

  if (newQueue== NULL) {
      exit(1); // return null pointer if memory isn't allocated
  }

  newQueue->localDataStructure = (command*)malloc( sizeof(command) * elements );

  if (newQueue->localDataStructure == NULL) {
      exit(1);// return null pointer if memory isn't allocated
  }

  // assign values to our new queue
  newQueue->currentCapacity=elements;

  newQueue->growOnDemand=growOnDemand; 

  newQueue->queueLock=FALSE;
  // make our queue empty
  return initializeQueue(newQueue,0);

}
Esempio n. 5
0
int main(){
	
	Queue *fila;
	int i, val;
	
	fila = createQueue();
	initializeQueue(fila);
	
	srand(time(NULL));

	for (i=10; i>0; i--)
	{

		if (enqueue(fila, rand()%30), &IntCmp)
		{
			printf("O valor foi inserido\n");
		}
		else
		{
			printf("Não há mais espaço na fila\n");
		}
	
	}
	for (i=0; i<4; i++)
	{
		if (dequeue(fila, &val))
		{
			printf("--%d\n", val);
		}
		else
		{
			printf("Não há nada na fila\n");
		}
	}

	if (peek(fila, &val)) 
	{
		printf("peek: %d\n", val);
	}
	else
	{
		printf("Não há nada na fila\n");
	}
	
	printf("Tamanho da fila: %d\n", sizeQueue(fila));
	
	if (isEmptyQueue(fila))
	{
		printf("A fila está vazia\n");
	}
	else
	{
		printf("A fila não está vazia\n");
	}	 	
	
	printQueue(fila);
return(0);
}
Queue::Queue (int size)
{
	maxQueueSize = size;
	initializeQueue ();

	//allocate array
	//it starts from 0 not 1
	list = new int [maxQueueSize - 1];
}
Esempio n. 7
0
/*
 * We'll setup all the queues that
 * need to be part of simulation
 * */
void initializeAllQueues(int debugId )
{
	/*setting up requisite number of concession clerk queues*/
	mtCb.queue[CC_QUEUE][cc_number].queueId = cc_number;
	mtCb.queue[CC_QUEUE][cc_number].queueType = CC_QUEUE;
	initializeQueue(debugId, &mtCb.queue[CC_QUEUE][cc_number]);
	queueLock[CC_QUEUE][cc_number] = mtCb.queue[CC_QUEUE][cc_number].name;
	CreateLock(mtCb.queue[CC_QUEUE][cc_number].name);
	queueCondVar[CC_QUEUE][cc_number] = mtCb.queue[CC_QUEUE][cc_number].name;
	CreateCV(mtCb.queue[CC_QUEUE][cc_number].name);
	addAddressToQueue(debugId, cc_number, CC_QUEUE, cc_number);
}
Esempio n. 8
0
static void test_remove_from_queue() {
    Queue *queue = (Queue *)malloc(sizeof(Queue));
    initializeQueue(queue);
    Thread *thread1 = malloc(sizeof(Thread));
    Thread *thread2 = malloc(sizeof(Thread));
    Thread *thread3 = malloc(sizeof(Thread));
    insertIntoQueue(queue, thread1);
    insertIntoQueue(queue, thread2);
    insertIntoQueue(queue, thread3);
    assert(sizeOfQueue(queue) == 3);
    removeFromQueue(queue, thread3);
    printQueue(queue);
    assert(sizeOfQueue(queue) == 2);
}
//inistialize the buffer pool
RC initBufferPool(BM_BufferPool *const bm, const char *const pageFileName,const int numPages, ReplacementStrategy strategy,void *stratData)
{
    countWrite=0;
    countRead=0;
    fh=(SM_FileHandle *)malloc(sizeof(SM_FileHandle));
    char* buff = (char *)calloc(PAGE_SIZE*numPages,sizeof(char));
    bm->pageFile=(char *)pageFileName;
    bm->numPages=numPages;
    bm->strategy=strategy;
    bm->mgmtData=buff;
    g_queue= (queue *)malloc(sizeof(queue));
    openPageFile (bm->pageFile, fh);
    initializeQueue(g_queue,bm);
    return RC_OK;
}
Esempio n. 10
0
static void test_insert_and_deque_for_empty_queue() {
    Queue *queue = (Queue *)malloc(sizeof(Queue));
    initializeQueue(queue);
    Thread thread2;
    Thread *thread1 = malloc(sizeof(Thread));
    ucontext_t ctxt;
    getcontext(&ctxt);
    thread1->uctxt = ctxt;
    insertIntoQueue(queue, thread1);
    assert(queue->front == queue->rear);
    insertIntoQueue(queue, &thread2);
    assert(queue->front->next == queue->rear);
    dequeue(queue);
    dequeue(queue);
    assert(queue->front == NULL && queue->rear == NULL);
}
Esempio n. 11
0
/************************************************************************************
*
*	increaseQueueCapacity
*
*	Increases the capacity of the queue
*      
*	Arguments:
*
*      Queue inputQueue - The input queue
*      unsigned short increaseAmount - Amount to which we will increase the size of
*       our queue
*
*	Return Value:
*
*		void
*
*************************************************************************************/
void increaseQueueCapacity(Queue inputQueue,unsigned short increaseAmount)
{

    

    inputQueue->currentCapacity+=increaseAmount;

    inputQueue->localDataStructure = (command*)realloc(inputQueue->localDataStructure, sizeof(command) * inputQueue->currentCapacity );

    if (inputQueue->localDataStructure == NULL) {
        exit(1); // return null pointer if memory isn't allocated
    }

    initializeQueue(inputQueue,inputQueue->currentCapacity-increaseAmount-1);

    
}
Esempio n. 12
0
int main(void) {
  int i;
  int readValue;
  circularQueue_t myQueue;

  initializeQueue(&myQueue);
  for (i = 0; i < MAX_ITEMS + 1; i++) {
    putItem(&myQueue, i);
  }
  printQueue(&myQueue);

  for (i = 0; i < MAX_ITEMS/2; i++) {
    getItem(&myQueue, &readValue);
    printf("readValue = %d\n", readValue);
  }
  printQueue(&myQueue);

  return 0;
}
Esempio n. 13
0
void BFS(graph *p, int v){
	int node_num = p->node_num;
	int i, v1;
	initializeQueue();
	enqueue(&v);
	
	visited[v] = 1;
	printf("%d ",v);

	while(!isEmpty()){
		v1 = *(int *)dequeue();
		for(i = 0; i < node_num; i++){
			if(p->matrix[v][i] == 1 && visited[i] == 0){
				visited[i] = 1;
				enqueue(&i);
				printf("%d ",i);
			}
		}
	}
}
Esempio n. 14
0
/*
 * We'll setup all the queues that
 * need to be part of simulation
 * */
void initializeAllQueues(int debugId )
{

	mtCb.queue[TC_QUEUE][tc_number].queueId = tc_number;
	mtCb.queue[TC_QUEUE][tc_number].queueType = TC_QUEUE;
	initializeQueue(debugId, &mtCb.queue[TC_QUEUE][tc_number]);

	/*Print("tc lock b4 created queuelock=%s type=%d id=%d\n", queueLock[TC_QUEUE][tc_number], TC_QUEUE, tc_number );*/

	queueLock[TC_QUEUE][tc_number] = mtCb.queue[TC_QUEUE][tc_number].name;
	CreateLock(queueLock[TC_QUEUE][tc_number]);

	/*Print("tc lock created queuelock=%s type=%d id=%d\n", queueLock[TC_QUEUE][tc_number], TC_QUEUE, tc_number );*/



	/*Print("tc lock b4 created queuelock=%s type=%d id=%d\n", queueCondVar[TC_QUEUE][tc_number], TC_QUEUE, tc_number );*/
	queueCondVar[TC_QUEUE][tc_number] = mtCb.queue[TC_QUEUE][tc_number].name;
	CreateCV(queueCondVar[TC_QUEUE][tc_number]);
	/*Print("tc lock created queuecondvar=%s type=%d id=%d\n", queueCondVar[TC_QUEUE][tc_number], TC_QUEUE, tc_number );*/

	addAddressToQueue(debugId, tc_number, TC_QUEUE, tc_number);
}
Esempio n. 15
0
int main()
{
	int n, i, e; // variables for the number of patients, an iterator and the ID of an emergency
	char c = '\0'; // variable for the commands

	// Getting the number of patients
	scanf("%d", &n);

	// Initializing the queue
	initializeQueue();

	// Enqueing all of the patients
	for (i = 1; i <= n; i++)
	{
		enqueue(i);
	}

	// Scanning the commands
	while (c != 'F')
	{
		scanf("%c", &c);

		switch(c)
		{
			case 'A':
				printf("%d ", dequeue());
				break;

			case 'E':
				scanf("%d ", &e);
				moveToFront(e);
				break;
		}
	}
	
	return 0;
}
Esempio n. 16
0
// Initializes the system (global variables)
// @par: none
// @ret: none
void initSystem(void) {
    host.numPrinters = MAX_PRINTERS;
    host.numScanners = MAX_SCANNERS;
    host.numModems = MAX_MODEMS;
    host.numDisks = MAX_DISKS;
    host.memSpaceMax = MAX_MEMSPACE;
    host.rtMemSpaceMax = MAX_RTMEMSPACE;
    host.rtMemSpaceUsed = 0;
    host.currentProcess = NULL;

    memset(host.printersAlloc, 0, MAX_PRINTERS);
    memset(host.scannersAlloc, 0, MAX_SCANNERS);
    memset(host.modemsAlloc, 0, MAX_MODEMS);
    memset(host.disksAlloc, 0, MAX_DISKS);
    memset(host.memSpace, 0, MAX_MEMSPACE);

    // Initialize all queues to be separate queues
    dispatcher = initializeQueue();
    realTimeQueue = initializeQueue();
    userJobQueue = initializeQueue();
    p1Queue = initializeQueue();
    p2Queue = initializeQueue();
    p3Queue = initializeQueue();
}
// ****************************************************************************
// *** Main Function **********************************************************
// ****************************************************************************
void main(void)
{
    	initialization();

	waterPrimeTimeOut /= upstrokeInterval;
	leakRateTimeOut /= upstrokeInterval;
	timeBetweenUpstrokes /= upstrokeInterval;

	// Do all of these values need to be reset each time around the loop? Or at the end of the day? 06-16-2014
	int handleMovement = 0; // Either 1 or no 0 if the handle moving upward
	int timeOutStatus = 0; // Used to keep track of the water prime timeout
	int hour = 0; // Hour of day
	float angleCurrent = 0; // Stores the current angle of the pump handle
	float anglePrevious = 0; // Stores the last recoreded angle of the pump handle
	float angleDelta = 0; // Stores the difference between the current and previous angles
	float upStroke = 0; // 0 if there is no upstroke, otherwise stores the delta angle
	float upStrokePrime = 0; // Stores the sum of the upstrokes for calculating the prime
	float upStrokeExtract = 0; // Stores the sum of the upstrokes for calculating volume
	float volumeEvent = 0; // Stores the volume extracted
	float extractionStartTime = 0; // The time of day (in seconds) when the extraction started
	float extractionEndTime = 0; // The time of day (in seconds) when the extraction ended
	float extractionDuration = 0; // The difference between the extraction start and end times
	long leakTimeCounter = 0; // Used to keep track of the leak time timeout
	float upStrokePrimeMeters = 0; // Stores the upstroke in meters
	float leakRate = 0; // Rate at which water is leaking from the rising main
	float leakTime = 0; // The number of milliseconds from when the user stops pumping until there is no water (min: 0, max: 10 minutes)
	long upStrokeDelayCounter = 0;

	while (1)
	{ //MAIN LOOP; repeats indefinitely
		////////////////////////////////////////////////////////////
		// Idle Handle Monitor Loop
		// 2 axis of the accelerometer are constantly polled for
		// motion in the upward direction by comparing angles
		////////////////////////////////////////////////////////////
		// Get the angle of the pump handle to measure against
		anglePrevious = getHandleAngle();
		float deltaAverage = 0, previousAverage = 0;
		initializeQueue(anglePrevious);
		previousAverage = queueAverage();
		// Set the handle movement to 0 (handle is not moving)
		handleMovement = 0;
		// Loop until the handle starts moving
		while (handleMovement == 0)
		{
                        debugHighLow(Pin4);
			if (prevHour != getHourI2C()){ //(prevDay != getDateI2C()){// it's a new day so send midNightMessage();
				midnightMessage();
			}
			// Delay for a short time
			delayMs(upstrokeInterval);
			// Get the current angle of the pump handle
			pushToQueue(getHandleAngle());
			//Calculate the change in angle of the pump handle
			deltaAverage = queueAverage() - previousAverage;
			previousAverage = queueAverage();
			// If the angle has changed, set the handleMovement flag
			if (deltaAverage > angleDeltaThreshold) //05-30-14 Test for small delta's
			{
				handleMovement = 1;
			}
		} //Exit loop when handle is moving
		/////////////////////////////////////////////////////////
		// Priming Loop
		// The total amount of upstroke is recorded while the
		// upper water sensor is checked to determine if the
		// pump has been primed
		/////////////////////////////////////////////////////////
		timeOutStatus = 0; // prepares timeoutstatus for new event
		// Get the angle of the pump handle to measure against
		anglePrevious = getHandleAngle();
		upStrokePrime = 0; // gets the variable ready for a new event
		while ((timeOutStatus < waterPrimeTimeOut) && !readWaterSensor())
		{       debugHighLow(Pin5);
			delayMs(upstrokeInterval);
			// Get the current angle of the pump handle
			angleCurrent = getHandleAngle();
			// Calculate the change in angle of the pump handle
			angleDelta = angleCurrent - anglePrevious;
			// If the pump angle has changed, update the up stroke, otherwise set it to 0
			if (angleDelta > angleDeltaThreshold)
			{
				upStroke = angleDelta;
			}
			else
			{
				upStroke = 0;
			}
			// Update the previous angle for the next calculation
			anglePrevious = angleCurrent;
			// If no upstroke is happening, increase the timeout
			if (upStroke == 0)
			{
				timeOutStatus++;
			}
			// Otherwise, reset the timeout because movement occurred
			else if (upStroke > 0)
			{
				timeOutStatus = 0;
				upStrokePrime += degToRad(upStroke); // Update the upStrokePrime
			}
		}
		// Convert to meters
		upStrokePrimeMeters = upStrokePrime * upstrokeToMeters;
		// Updates the longestPrime
		if (upStrokePrimeMeters > longestPrime)
		{
			longestPrime = upStrokePrimeMeters;
		}
		///////////////////////////////////////////////////////
		// Volume Calculation loop
		// Tracks the upStroke for the water being extracted
		//(in next loop -->) as well as the time in milliseconds taken for water to leak
		///////////////////////////////////////////////////////
		// Reset the upstroke extract
		upStrokeExtract = 0;
		// Get the start time (in seconds) of the extraction
		extractionStartTime = timeStamp();
		// Get the angle of the pump handle to measure against
		anglePrevious = getHandleAngle();
		float averageAngle = 0;
		float currentAverage = 0;
		previousAverage = 0;
		deltaAverage = 0;
		// Initialize the queue
		initializeQueue(anglePrevious);
		previousAverage = queueAverage();
		// Used to count the number of milliseonds between upstrokes
		upStrokeDelayCounter = 0;
		// Used to keep track of the total time passed in milliseconds
		leakTime = 0;
		// Used to keep track of how many milliseconds have passed
		int millisecondCounter = 0;
		// Reset upstroke
		upStroke = 0;
		float highest = previousAverage, lowest = previousAverage;
		int checkHighest = 1, checkLowest = 1;
		while (readWaterSensor() && (upStrokeDelayCounter < timeBetweenUpstrokes))
		{
                        debugHighLow(Pin7);
			if (millisecondCounter > upstrokeInterval)
			{
				millisecondCounter = 0; // Reset the counter
				// Get the current angle of the pump handle
				pushToQueue(getHandleAngle());
				// Get the average of the angles in the queue
				averageAngle = queueAverage();
				currentAverage = averageAngle;
				deltaAverage = currentAverage - previousAverage;
				previousAverage = currentAverage;
				if (averageAngle > highest)
				{
					highest = averageAngle;
				}
				else if (averageAngle < lowest)
				{
					lowest = averageAngle;
				}
				if (((highest - averageAngle) > minimumAngleDelta) && checkHighest)
				{
					upStrokeExtract += degToRad(highest - lowest);
					lowest = 100;
					checkHighest = 0;
					checkLowest = 1;
				}
				else if (((averageAngle - lowest) > minimumAngleDelta) && checkLowest)
				{
					highest = -100;
					checkLowest = 0;
					checkHighest = 1;
				}
				//If the handle moved, set the upStroke
				if (deltaAverage > 1.2)
				{
					upStrokeDelayCounter = 0; // Reset the upstroke counter
					upStroke = deltaAverage;
				}
				else
				{
					upStroke = 0;
					upStrokeDelayCounter++;
				}
			}
			if (upStroke == 0)
			{
				leakTime++;
			}
			else
			{
				leakTime = 0;
			}
			millisecondCounter++;
			delayMs(1);
		}
		extractionEndTime = timeStamp();
		// Check for extraction end time being less (if someone starts
		// before 12 AM and ends after 12 AM)
		if (extractionEndTime < extractionStartTime)
		{
			extractionDuration = (86400 - extractionEndTime) + extractionStartTime;
		}
		else
		{
			extractionDuration = extractionEndTime - extractionStartTime;
		}
		///////////////////////////////////////////////////////
		// Leakage Rate loop
		///////////////////////////////////////////////////////
		// Get the angle of the pump handle to measure against
		anglePrevious = getHandleAngle();
		// Used to keep track of how many milliseconds have passed
		millisecondCounter = 0;
		// Reset the counter for the leak timeout
		leakTimeCounter = 0;
		while (readWaterSensor() && (leakTimeCounter < leakRateTimeOut))
		{
                        debugHighLow(Pin9);
			if (millisecondCounter > upstrokeInterval)
			{
				millisecondCounter = 0; // Reset the counter
				// Get the current angle of the pump handle
				angleCurrent = getHandleAngle();
				//Calculate the change in angle of the pump handle
				angleDelta = angleCurrent - anglePrevious;
				// Update the previous angle for the next calculation
				anglePrevious = angleCurrent;
				leakTimeCounter++;
				// If the handle moved more than 2 degrees, we will consider that an
				// intentional pump and break out of the loop (2 is in radians)
				if (angleDelta > angleDeltaThreshold)
				{
					break;
				}
			}
			millisecondCounter++;
			leakTime++;
			delayMs(1);
		}
		//Check if water is present - make sure this function works!
		if (readWaterSensor())
		{
			leakRate = 0;
		}
		else
		{
			// Add one to leakTime to prevent divide by 0 error (and divide by 1000 to get milliseconds into seconds
			leakRate = leakSensorVolume / ((leakTime + 1) / 1000.0); // Leak rate is L/s
		}
		if (leakRate > leakRateLong)
		{
			leakRateLong = leakRate;
		}
		volumeEvent = (MKII * upStrokeExtract) - (leakRate * extractionDuration);
		hour = getHourI2C();
		switch (hour / 2)
		{ //organize extaction into 2 hours bins
			//does this work? what happens if odd hour?
			//wouldn't it be a float and not enter--is that the purpose then, is that what we want?? 06-17-2014
		case 0:
			volume02 = volume02 + volumeEvent;
			break;
		case 1:
			volume24 = volume24 + volumeEvent;
			break;
		case 3:
			volume46 = volume46 + volumeEvent;
			break;
		case 4:
			volume68 = volume68 + volumeEvent;
			break;
		case 5:
			volume810 = volume810 + volumeEvent;
			break;
		case 6:
			volume1012 = volume1012 + volumeEvent;
			break;
		case 7:
			volume1214 = volume1214 + volumeEvent;
			break;
		case 8:
			volume1416 = volume1416 + volumeEvent;
			break;
		case 9:
			volume1618 = volume1618 + volumeEvent;
			break;
		case 10:
			volume1820 = volume1820 + volumeEvent;
			break;
		case 11:
			volume2022 = volume2022 + volumeEvent;
			break;
		case 12:
			volume2224 = volume2224 + volumeEvent;
			break;
		}
	} // End of main loop
}
Esempio n. 18
0
/**
* Put the elements on the vector
//reading transversely on tree
//  Start --->  /A\
//    B\        /C\
//      D      E   F ---> End
*/
static void setArrayValueQTree(DATA_QUADTREE* param, int size, int n_args, DATA_QUADTREE* vetor_node[])
{

    DATA_QUADTREE *currentNode;
    Queue q;
    int index=0;
    int i=0;
    int j=0;
    int k = 0;
    COLOR* HL_color_list = (COLOR*)malloc(sizeof(COLOR));



    initializeQueue(&q);

    enqueue(&q, param);

    for(i=0; i<size; i++)
    {

        currentNode = frontQPTree(&q);

        if(currentNode != NULL)
        {
            convertValue(&currentNode->valor,currentNode->valor,  qVector[index].value);

            for(j=0; j < 4; j++)
                qVector[index].plotLine[j]=currentNode->filhos[j]!=NULL?1:0;

            qVector[index].isNull=0;
            qVector[index].aux_blue_tree = aux_blue_qtree;
            qVector[index].aux_green_tree = aux_green_qtree;
            qVector[index].aux_red_tree = aux_red_qtree;


            for(k = 0; k < n_args; k++)
            {
                if(param == vetor_node[k])
                {
                    HL_color_list = getHLColor(k+1);
                    qVector[index].aux_red_tree   = HL_color_list->red;
                    qVector[index].aux_green_tree = HL_color_list->green;
                    qVector[index].aux_blue_tree  = HL_color_list->blue;
                    break;
                }
            }



        }

        index+=1;

        for(j=0; j < 4; j++)
            enqueue(&q, currentNode!=NULL?currentNode->filhos[j]:NULL);



        dequeue(&q);
    }


}
Esempio n. 19
0
// Updates the dispatcher
// @par: int    current time (quantum)
// @ret: int    1 for process put into real time queue
// @ret: int    0 otherwise
int updateDispatcher(int time) {
    // Create a pointer to the dispatcher so we don't modify dispatcher directly unless we need to
    Queue *queuePtr = dispatcher;

    // Create a new queue for elements that weren't able to be added
    Queue *newDispatcher = initializeQueue();

    int rtQUpdated = 0;

    // Checks if dispatcher is empty
    if (!(queuePtr)) {
        printf("The queue is empty!\n\n");
        return 0;
    }

    // Iterate through each element in the queue
    int i = 0;
    int count = numElems(queuePtr);

    // If the first process is NULL, we don't want to iterate through them
    // Double check that there are elements in queue
    if (queuePtr->process == NULL) {
        i = count;
    }

    // Keep an indicator to see if anything breaks
    int broken = 0;

    // Iterate through each element in the dispatcher
    while (i < count) {
        // Dequeue the next process from the queue
        PCB *currentProcess = dequeueProcess(&queuePtr)->process;

        // Queue is empty
        // Triple check
        if (currentProcess == NULL) {
            printf("BROKEN!\n");
            broken = 1;
            break;
        }

        // If the process has "arrived", attempt to allocate resources to it
        if (time >= currentProcess->arrivalTime) {
            // Attempt to allocate resources to the process.
            int allocResult = allocateResources(currentProcess);

            if (allocResult) {
                // Resources were allocated successfully
                printf("* INITIALIZED pid: %d", currentProcess->pid);
                if (currentProcess->priority == 0) {
                    rtQUpdated = 1;
                    printf(", a real time process");
                }
                printf("\n\n");

                // Send the process to join the appropriate priority queue
                enqueueToPriority(currentProcess);
            } else {
                // Resources could not be allocated, move the process back on the dispatcher queue
                enqueueProcess(newDispatcher, currentProcess);
            }
        } else {
            // The time has not come for this process, add it to the new dispatcher
            enqueueProcess(newDispatcher, currentProcess);
        }

        i++;
    }

    // If the queue wasn't broken
    if (!broken) {
        if (dispatcher == NULL) {
            cleanQueue(dispatcher);
        }
        dispatcher = newDispatcher;
    }

    return rtQUpdated;
}
Esempio n. 20
0
Queue *createAndInitializeQueue() {
	Queue *q = (Queue *)malloc(sizeof(Queue));
	initializeQueue(q);
	return q;
}	
Esempio n. 21
0
static void test_initialize_queue() {
    Queue *queue = (Queue *)malloc(sizeof(Queue));
    initializeQueue(queue);
    assert(queue->front == NULL && queue->rear == NULL);
    free(queue);
}
// ****************************************************************************
// *** Main Function **********************************************************
// ****************************************************************************
void main(void)
{
    	initialization();
        sendTextMessage("What Hath God Wrought? Number 1");

        while(1){
//            sendTextMessage("What Hath God Wrought \r\n");
//            int angleForMessage = getHandleAngle();
//            char angleMessage[20];
//            angleMessage[0]=0;
//            longToString(angleForMessage, angleMessage);
//
//            concat(angleMessage, "\r \n");
//            sendMessage("angle: ");
//            sendMessage(angleMessage);
        }


	waterPrimeTimeOut /= upstrokeInterval;
	leakRateTimeOut /= upstrokeInterval;
	//timeBetweenUpstrokes /= upstrokeInterval;

	// Do all of these values need to be reset each time around the loop? Or at the end of the day? 06-16-2014
	int handleMovement = 0; // Either 1 or no 0 if the handle moving upward
	int timeOutStatus = 0; // Used to keep track of the water prime timeout
	int hour = 0; // Hour of day
	float angleCurrent = 0; // Stores the current angle of the pump handle
	float anglePrevious = 0; // Stores the last recoreded angle of the pump handle
	float angleDelta = 0; // Stores the difference between the current and previous angles
	float upStroke = 0; // 0 if there is no upstroke, otherwise stores the delta angle
	float upStrokePrime = 0; // Stores the sum of the upstrokes for calculating the prime
	float upStrokeExtract = 0; // Stores the sum of the upstrokes for calculating volume
	float volumeEvent = 0; // Stores the volume extracted
        float leakRatePrevious = 0; // Stores the previous Leak Rate incase if someone stats to pump before leakage can be measured
        //float extractionStartTime = 0; // The time of day (in seconds) when the extraction started
	//float extractionEndTime = 0; // The time of day (in seconds) when the extraction ended
	//float extractionDuration = 0; // The difference between the extraction start and end times
	long leakTimeCounter = 0; // Used to keep track of the leak time timeout
	float upStrokePrimeMeters = 0; // Stores the upstroke in meters
	float leakRate = 0; // Rate at which water is leaking from the rising main
//	float leakTime = 0; // The number of milliseconds from when the user stops pumping until there is no water (min: 0, max: 10 minutes)
//	long upStrokeDelayCounter = 0;
//        int currentHour;
        int currentDay;
        int currentHourDepthSensor;

        float deltaAverage;

	while (1)
	{ //MAIN LOOP; repeats indefinitely
		////////////////////////////////////////////////////////////
		// Idle Handle Monitor Loop
		// 2 axis of the accelerometer are constantly polled for
		// motion in the upward direction by comparing angles
		////////////////////////////////////////////////////////////
		// Get the angle of the pump handle to measure against
		anglePrevious = getHandleAngle();
		float previousAverage = 0;
		// Set the handle movement to 0 (handle is not moving)
		handleMovement = 0;
		// Loop until the handle starts moving
                float angleAccumulated=0;
		while (handleMovement == 0)
		{
                          currentDay = getDateI2C();
			if ( prevDay != currentDay){ //(prevDay != getDateI2C()){// it's a new day so send midNightMessage();
                                batteryFloat = batteryLevel();
				midnightMessage();
			}
                          if (depthSensorInUse == 1){ // if the Depth sensor is present
                              delayMs(1000);
                              int currentDayDepthSensor = BcdToDec(getDateI2C());
                              delayMs(1000);
                          if ((BcdToDec(getHourI2C() == 12) && (prevDayDepthSensor != currentDayDepthSensor)));
                          midDayDepthRead();
                          }

			delayMs(upstrokeInterval); // Delay for a short time
                        float newAngle = getHandleAngle();
                        float deltaAngle = abs(newAngle - anglePrevious);
                        anglePrevious = newAngle;
                        if (deltaAngle > 2){ // prevents floating accelerometer values when it's not actually moving
                        angleAccumulated += deltaAngle;
                        }
			// If the angle has changed, set the handleMovement flag
			if (angleAccumulated > 5) //05-30-14 Test for small delta's used to be angleDeltaThreshold
			{
				handleMovement = 1;
			}
		}
                /////////////////////////////////////////////////////////
		// Priming Loop
		// The total amount of upstroke is recorded while the
		// upper water sensor is checked to determine if the
		// pump has been primed
		/////////////////////////////////////////////////////////
		timeOutStatus = 0; // prepares timeoutstatus for new event
		// Get the angle of the pump handle to measure against
		anglePrevious = getHandleAngle();
		upStrokePrime = 0; // gets the variable ready for a new event
                upStroke = 0; // gets variable ready for new event

                // averaging angle Code 9/17/2015
                initializeQueue(anglePrevious);
		previousAverage = queueAverage();
                // Averaging angle code

		while ((timeOutStatus < waterPrimeTimeOut) && !readWaterSensor())
		{
			delayMs(upstrokeInterval);  // delay a short time (10ms)

                        // averaging angle Code 9/17/2015
                        pushToQueue(getHandleAngle()); //get Current angle of the pump handle
                        deltaAverage = queueAverage() - previousAverage();
                        previousAverage = queueAverage();
                        
                        
                        // end averaging angle Code

                        angleCurrent = getHandleAngle(); // Get the current angle of the pump handle
			angleDelta = angleCurrent - anglePrevious; // Calculate the change in angle of the pump handle
                        //if(angleDelta > 5){
                        if (deltaAverage > 5){ // averaging angle code 9/17/2015
                            upStroke + = deltaAverage; // angle Code 9/17/2015
                           // upStroke += angleDelta;
                            upStrokePrime += degToRad(upStroke); // Update the upStrokePrime
                            timeOutStatus=0;
                        // upstroke and current angle
			}
                        else{
                        timeOutStatus++;}
			anglePrevious = angleCurrent; // Update the previous angle for the next calculation
			}