Ejemplo n.º 1
0
/*		Deepest Node in Binary Tree		*/
	tree *depthOfTree(tree **root)
	{
		queue *Q;	
		tree *temp,*temp1;

		if(!(*root)){
		return NULL;}
	
	   	Q=create();
	   	Enqueue(Q,*root);
	   	while(!(IsEmptyQueue(Q)))
	   	{
	   		temp=Dequeue(Q);
	   		if(temp->left)
	   			Enqueue(Q,temp->left);

	   		if(temp->right)
	   			Enqueue(Q,temp->right);
	   	}
	   deleteQueue(Q);
	 return temp;  	
	}
Ejemplo n.º 2
0
	int heightOfBinary(tree *root)
	{ 	
		int level=1;
		queue *Q;	
		
		if(!root){
		return 0;}
	
	   	Q=create();
	   	Enqueue(Q,root);
	   	//End Of first Level
	   	Enqueue(Q,NULL);
	   	
	   	while(!(IsEmptyQueue(Q)))
	   	{
	   		root=Dequeue(Q);
			
	   		//completion of current Level
	   		if(root == NULL)
	   		{
	   			if(!IsEmptyQueue(Q)){
	   			Enqueue(Q,NULL);
	   			level++;
	   			}
	   		}
	   		else
	   		{
	   		if(root->left)
	   			Enqueue(Q,root->left);
			
	   		if(root->right){
	   			Enqueue(Q,root->right);
		   		}
	   		}
	   	}
	   	deleteQueue(Q);
	 return level;  	
	}
Ejemplo n.º 3
0
void MyThreadJoinAll(void) {
	if (debug) printf("***** MyThreadJoinAll *****\n");
	if (debug) printf("***** Running   %i *****\n", running_thread->id);
	MyQueue * children = running_thread->children;
	if(!isEmpty(children)) {
		running_thread->state = 2;
		running_thread->join_all = true;
		Enqueue(running_thread, blockedQ, 1);

		Thread * blocked_thread = running_thread;

		running_thread = readyQ->front;
		Dequeue(readyQ, 0);
		running_thread->state = 1;

		if (debug) printf("***** Blocked   %i   *****\n", blocked_thread->id);
		if (debug) printf("***** Running   %i *****\n", running_thread->id);

		if (queues) PrintQueue(readyQ, 0);
		if (queues) PrintQueue(blockedQ, 1);
		swapcontext(blocked_thread->context, running_thread->context);
	}
}
int findmaxwithoutrecursion(struct node *root)
{
    int max=INT_MIN;
        struct Queue* queue = createQueue(SIZE);

    Enqueue(root, queue);

    while (!isEmpty(queue))
    {
        struct node* temp = Dequeue(queue);

        if(max<temp->data)
            max=temp->data;

        if (temp->left)
            Enqueue(temp->left, queue);

        if (temp->right)
            Enqueue(temp->right, queue);
    }
            return max;

}
Ejemplo n.º 5
0
void Enqueue(Queue Q, ElementType Value)
{
  ElementType *Buffer;
  int i;

  if (IsFull(Q))
  {
    Buffer = malloc(sizeof(ElementType) * Q -> Capacity * 2);
    i = 0;
    while (!IsEmpty(Q))
      Buffer[i++] = Dequeue(Q);

    Q -> Front = 0;
    Q -> Rear = i;
    Q -> Capacity *= 2;
    free(Q -> Next);
    Q -> Next = Buffer;
  }

  Q -> Next[Q -> Rear] = Value;
  Q -> Rear = Succ(Q, Q -> Rear);
  return;
}
Ejemplo n.º 6
0
    /* virtual */ void
QCDiskQueue::Queue::Run(
    int inThreadIndex)
{
    QCStMutexLocker theLock(mMutex);
    QCASSERT(inThreadIndex >= 0 && inThreadIndex < mThreadCount);
    int* const          theFdPtr    = mFdPtr +
        mFdCount / mThreadCount * inThreadIndex;
    struct iovec* const theIoVecPtr = mIoVecPtr +
        mIoVecPerThreadCount * inThreadIndex;
    while (mRunFlag) {
        Request* theReqPtr;
        while (! (theReqPtr = Dequeue()) && mRunFlag) {
            mWorkCond.Wait(mMutex);
        }
        if (mRunFlag) {
            QCASSERT(theReqPtr);
            Process(*theReqPtr, theFdPtr, theIoVecPtr);
        } else if (theReqPtr) {
            Cancel(*theReqPtr);
        }
    }
}
int findmaxlevel(struct node* root)
{
    struct Queue* Q=createQueue(SIZE);
    struct node* temp;
    int sum=0,l=0;

    if(!root)
        return 0;
    Enqueue(root,Q);
    Enqueue(NULL,Q);

    while(!isEmpty(Q))
    {
        temp=Dequeue(Q);
        if(!temp)
        {
           if(sum>max_sum)
           {
               max_sum=sum;
               max_level=l;
           }
           sum=0;
        if(!isEmpty(Q))
           Enqueue(NULL,Q);
           l++;
        }
        else
        {
        sum=sum+temp->data;
            if(temp->left)
               Enqueue(temp->left,Q);
            if(temp->right)
               Enqueue(temp->right,Q);
        }
    }
    return max_level;
}
Ejemplo n.º 8
0
void LevelOrderIterative( TreeNode *root )
{
	if( !root )
	{
		return;
	}

	Enqueue( root );
	Enqueue( NULL );

	while( !IsQueueEmpty() )
	{
		root = Dequeue();

		if( !root )
		{
			if( !IsQueueEmpty() )
			{
				Enqueue( NULL );
				continue;
			}
			else
			{
				break;
			}
		}

		root->next = Queue[ front ];

		if( root->left )
			Enqueue( root->left );

		if( root->right )
			Enqueue( root->right );
	}

}
Ejemplo n.º 9
0
int Bfs(int presentVertex,int *visited, int cluster){
	int tempSize=0,success=0;
	int flag; /*Flag in case the diameter is infinite*/
	edge iterEdges;
	Queue *Q = CreateQueue(vertexNum); /*creates an empty queue in the size of all the vertices*/
	visited[presentVertex] = 1;
	/* Iterate through all the vertices connected to the presentVertex and perform bfs on those
	vertices if they are not visited before */
	Enqueue(Q,presentVertex);
	while(Q->size){
		flag=0;
		presentVertex = Front(Q);
		Dequeue(Q);
		iterEdges=vertices[presentVertex]->edges->head;
		while(iterEdges!=NULL){
			if(iterEdges->inCluster==1 ||iterEdges->inCluster==3){
				flag=1;
				if(visited[iterEdges->id_vertex]==0){
					if((vertices[iterEdges->id_vertex])->ClusterBelonging==cluster){
						Enqueue(Q,iterEdges->id_vertex);
						visited[iterEdges->id_vertex]=1;
						success=1;
					}
				}
			}
			iterEdges=iterEdges->next;
		}
		tempSize=tempSize+success;
		success=0;
	}
	free(Q);
	if (0==flag){
		tempSize=-1; /*-1 means "infinite"*/
	}
	return tempSize;
}
void CustomerList::RemoveCustomer(Customer &someCustomer)
{
	Node<Customer> * traversePtr;
	Node<Customer> * actionPtr;

	if(isEmpty())
	{
		//		cout << "Can't Dequeue an empty list" << endl;
		throw EmptyList();
	}

	traversePtr = _head;
	int index = 0;

	while (index < _listLimit && traversePtr != NULL && !(traversePtr->GetData() == someCustomer))
	{

		traversePtr = traversePtr->GetNext();
		index++;
	}

	// overloaded operator
	if (traversePtr->GetData() == someCustomer)
	{
		// head deletion
		if (traversePtr == _head)
		{
			Dequeue();

		}
		// end deletion
		else if (traversePtr == _tail)
		{
			_tail = _tail->GetPrevious();


			_tail->SetNext(NULL);
			//				_tail->_next = NULL;

			traversePtr->Orphan();

			delete traversePtr;

			//Decrements the _nodeCount
			DecrementCount();

		}
		// middle deletion
		else
		{
			actionPtr = traversePtr->GetPrevious();
			actionPtr->SetNext(traversePtr->GetNext());
			traversePtr->SetNext(traversePtr->GetNext());
			traversePtr->SetPrevious(actionPtr);
			traversePtr->Orphan();
			delete traversePtr;
			//Decrements the _nodeCount
			DecrementCount();

		}

	}

	if (index == _listLimit && traversePtr == NULL)
	{
		// throw exception class if not found.
		traversePtr = NULL;
		throw NotFound();
	}
}
Ejemplo n.º 11
0
void runMLPQ(int quantum)

{


int current_task = 0;


while (Pior1->piority_task !=NULL){
	
	Pior1->piority_task[current_task].length -= quantum;
	
	if (Pior1->piority_task[current_task].length <=0){
		Dequeue(Pior1);
		
	}
	
	current_task ++;
}
current_task =0;
while (Pior2->piority_task !=NULL&&Pior1->piority_task !=NULL){
	
	Pior2->piority_task[current_task].length -= quantum;
	
	if (Pior2->piority_task[current_task].length <=0){
		Dequeue(Pior2);
		
	}
	
	current_task ++;
}
current_task =0;
while (Pior3->piority_task !=NULL&&Pior1->piority_task !=NULL&&Pior2->piority_task !=NULL){
	
	Pior3->piority_task[current_task].length -= quantum;
	
	if (Pior3->piority_task[current_task].length <=0){
		Dequeue(Pior3);
		
	}
	
	current_task ++;
}
current_task =0;
while (Pior4->piority_task !=NULL&&Pior1->piority_task !=NULL&&Pior3->piority_task !=NULL&&Pior2->piority_task !=NULL){
	
	Pior4->piority_task[current_task].length -= quantum;
	
	if (Pior4->piority_task[current_task].length <=0){
		Dequeue(Pior4);
		
	}
	
	current_task ++;
}






/*if piority queue 1 is not empty*/
/*run robin Queue 1*/

/*Continue with each queue*/


}
Ejemplo n.º 12
0
 ~Queue() {
     while (head)Dequeue();
 }
Ejemplo n.º 13
0
int
main()
{
    array = (int*)ShmAllocate(sizeof(int)*(SIZE+3));  // queue[SIZE], head, tail, count
    int x, i, j, seminit = 1, y;
    int pid[NUM_DEQUEUER+NUM_ENQUEUER];

    for (i=0; i<SIZE; i++) array[i] = -1;
    array[SIZE] = 0;
    array[SIZE+1] = 0;
    array[SIZE+2] = 0;

    semid = SemGet(SEM_KEY1);
    SemCtl(semid, SYNCH_SET, &seminit);

    stdoutsemid = SemGet(SEM_KEY2);
    SemCtl(stdoutsemid, SYNCH_SET, &seminit);

    notFullid = CondGet(COND_KEY1);
    notEmptyid = CondGet(COND_KEY2);

    int temp;
    temp = -11;
    SemCtl(semid,SYNCH_GET,&temp);
    PrintInt(temp);
    for (i=0; i<NUM_DEQUEUER; i++) {
       x = Fork();
       if (x == 0) {
          for (j=0; j<NUM_DEQUEUE_OP; j++) {
             x = Dequeue (i, &y);
             SemOp(stdoutsemid, -1);
             PrintString("Dequeuer ");
             PrintInt(i);
             PrintString(": Got ");
             PrintInt(x);
             PrintString(" from slot ");
             PrintInt(y);
             PrintChar('\n');
             SemOp(stdoutsemid, 1);
          }
          Exit(DEQUEUE_EXIT_CODE);
       }
       pid[i] = x;
    }
    
    for (i=0; i<NUM_ENQUEUER; i++) {
       x = Fork();
       if (x == 0) {
          x = i*NUM_ENQUEUE_OP;
          for (j=0; j<NUM_ENQUEUE_OP; j++) {
             y = Enqueue (x+j, i);
             SemOp(stdoutsemid, -1);
             PrintString("Enqueuer ");
             PrintInt(i);
             PrintString(": Inserted ");
             PrintInt(x+j);
             PrintString(" in slot ");
             PrintInt(y);
             PrintChar('\n');
             SemOp(stdoutsemid, 1);
          }
          Exit(ENQUEUE_EXIT_CODE);
       }
       pid[i+NUM_DEQUEUER] = x;
    }

    for (i=0; i<NUM_DEQUEUER+NUM_ENQUEUER; i++) {
       x = Join(pid[i]);
       SemOp(stdoutsemid, -1);
       PrintString("Parent joined with ");
       PrintInt(pid[i]);
       PrintString(" having exit code ");
       PrintInt(x);
       PrintChar('\n');
       SemOp(stdoutsemid, 1);
    }
    SemCtl(semid, SYNCH_REMOVE, 0);
    SemCtl(stdoutsemid, SYNCH_REMOVE, 0);
    CondRemove(notFullid);
    CondRemove(notEmptyid);

    return 0;
}
void Opportunity_Action_Repair_Installation::Execute(AiMain *ai)
{

    sint32 node_idx, node_num;

    node_num = m_queue_len;

    Pillaged_Node *p=NULL;
    BOOL best_road_ok;
    sint32 road_type;
    BOOL build_success;
    sint32 stored = ai->m_player->GetMaterialsStored();
    sint32 cost;
    ERR_BUILD_INST err;
    sint32 o;
    BOOL make_grass;
    sint32 extra_data;

    for (node_idx=0; node_idx<node_num; node_idx++) {
        p = Dequeue();
        Assert(p);
        build_success = FALSE;

        if (p->m_fix_me_by <= ai->m_round_count->GetRound()) {

            if (0  == p->m_inst) {

                if (fz_min_num_dirty_tiles < m_dirty_tile_count) {
                    if (ai->m_world->CanBeIrrigated(&(p->m_pos))) {
                        make_grass = ai->m_rand->Next(100) < 70;
                    } else {
                        make_grass = ai->m_rand->Next(100) < 30;
                    }

                    if (make_grass) {
                        extra_data = TERRAIN_GRASSLAND;
                    } else {
                        extra_data = TERRAIN_HILL;
                    }

                     cost = ai->m_installationDB->GetCost(0 , &(p->m_pos), extra_data);
                     o = ai->m_world->GetArmyOwner(&(p->m_pos));
                     if (((cost + 2000) <= stored) && ((o == ai->m_my_player_id) || (o == -1))) {
                         ai->m_installationDB->CanBuildHere(0 , extra_data, &(p->m_pos), &err);
                         if ((ERR_BUILD_INST_OK == err) || (ERR_BUILD_INST_UPGRADE == err)) {
                             build_success = ai->m_installationDB->ConstructInstallation(0 , extra_data,
                                 &(p->m_pos));
                             if (build_success) {
                                 m_dirty_tile_count--;
                                 stored -= cost;
                             }
                         }
                     }
                }

            } else {

                if (0  == p->m_inst) {
                    road_type = 0 ;
                } else {
                    best_road_ok = ai->m_science_agent->GetBestRoadType(road_type);
                    Assert(best_road_ok);
                }

                 cost = ai->m_installationDB->GetCost(road_type, &(p->m_pos), 0);
                 if (cost <= stored) {

                     o = ai->m_world->GetArmyOwner(&(p->m_pos));
                     if ((o == ai->m_my_player_id) || (o == -1)) {
                         ai->m_installationDB->CanBuildHere(road_type, 0, &(p->m_pos), &err);
                         if ((ERR_BUILD_INST_OK == err) || (ERR_BUILD_INST_UPGRADE == err)) {
                             build_success = ai->m_installationDB->ConstructInstallation(road_type, 0,
                                 &(p->m_pos));
                             if (build_success) {
                                 stored -= cost;
                             }
                         }
                     }

                     if (!build_success) {
                        p->m_fix_me_by += 5;
                        p->m_attempt_count++;
                     }
                 }
            }

            if (!build_success && (p->m_attempt_count<4)) {
                Enqueue(p);
            } else {
                delete p;
                p=NULL;
            }
        }
    }
}
Ejemplo n.º 15
0
unsigned char SerialGetChar2(void)
{
  return Dequeue(&serialRxQueue2); /* get a byte by dequeuing the Rx Queue */
}
Ejemplo n.º 16
0
int main(void)
{
	int i,j;
	int N,M;
	int x_cur = 0, y_cur = 0;
	int result = 0 ;
	int length = 1;
	Queue q;
	Data dequeData;
	QueueInit(&q);

//입력을 받는다
	scanf("%d %d",&N,&M);
	
 
	for(j=0; j<N; j++)
	{
		for(i=0; i<M; i++)
		{
			scanf("%d",&data[i][j].value);
			data[i][j].use = 0;
		}
	}

	//printf("test value %d\n",data[1][1].value);
	data[0][0].x_cur = 0;
	data[0][0].y_cur = 0; 
	data[0][0].length = length;
	Enqueue(&q,&data[0][0]);

	while(!QIsEmpty(&q))
	{
			//printf("deque\n");
			//printf("data[0][0] : %d %d\n",data[0][0].x_cur,data[0][0].y_cur);
			
			dequeData = Dequeue(&q);
			data[dequeData.x_cur][dequeData.y_cur].use = 1;
			//printf("x_cur : %d y_cur : %d\n", dequeData.x_cur, dequeData.y_cur);
			//printf("dequeData.value %d\n",dequeData.value);		
			if((data[dequeData.x_cur][dequeData.y_cur].value == 1 ))
			{
		
				if((dequeData.x_cur+1 < M)&& (data[dequeData.x_cur+1][dequeData.y_cur].use == 0))
				{
					//printf("x_cur +1 enqueue\n");
					data[dequeData.x_cur+1][dequeData.y_cur].length = dequeData.length + 1 ;
					data[dequeData.x_cur+1][dequeData.y_cur].x_cur = dequeData.x_cur + 1;  
					data[dequeData.x_cur+1][dequeData.y_cur].y_cur = dequeData.y_cur;
					Enqueue(&q,&data[dequeData.x_cur+1][dequeData.y_cur]);		
				}
				if((dequeData.y_cur+1 < N)&& (data[dequeData.x_cur][dequeData.y_cur+1].use == 0))
				{
					//printf("y_cur +1 enqueue\n");
					data[dequeData.x_cur][dequeData.y_cur+1].length = dequeData.length + 1 ;
					data[dequeData.x_cur][dequeData.y_cur+1].x_cur = dequeData.x_cur;
					data[dequeData.x_cur][dequeData.y_cur+1].y_cur = dequeData.y_cur + 1;
					Enqueue(&q,&data[dequeData.x_cur][dequeData.y_cur+1]);		
				}
				if((0 <= dequeData.x_cur-1)&& (data[dequeData.x_cur-1][dequeData.y_cur].use == 0))
				{
					//printf("x_cur -1 enqueue\n");
					data[dequeData.x_cur-1][dequeData.y_cur].length = dequeData.length + 1 ;
					data[dequeData.x_cur-1][dequeData.y_cur].x_cur = dequeData.x_cur - 1;  
					data[dequeData.x_cur-1][dequeData.y_cur].y_cur = dequeData.y_cur;
					Enqueue(&q,&data[dequeData.x_cur-1][dequeData.y_cur]);				
				}
				if((0 <= dequeData.y_cur-1) && (data[dequeData.x_cur][dequeData.y_cur-1].use == 0))
				{
					//printf("y_cur -1 enqueue\n");
					data[dequeData.x_cur][dequeData.y_cur-1].length = dequeData.length + 1 ;
					data[dequeData.x_cur][dequeData.y_cur-1].x_cur = dequeData.x_cur;  
					data[dequeData.x_cur][dequeData.y_cur-1].y_cur = dequeData.y_cur-1;
					Enqueue(&q,&data[dequeData.x_cur][dequeData.y_cur-1]);				
				}
			}
			
	}


	printf("%d\n",data[M-1][N-1].length);
							
	return 0;
}
Ejemplo n.º 17
0
template <typename T> T PriorityQueue<T>::Dequeue()
{
	int priority;
	return Dequeue(priority);
}
Ejemplo n.º 18
0
static bool _ReaderRun(ThreadData _reader) {
    Reader* reader = (Reader*)_reader;
    QueueItem* item = NewQueueItem();
    Connection* connection = NULL;
    SelectionKey* key = NULL;
    int numConnectionsReady = 0;

    while(Dequeue(reader->queue, item, false)) {
        switch(QueueItemGetType(item)) {
            case AIO4C_QUEUE_ITEM_EXIT:
                FreeQueueItem(&item);
                return false;
            case AIO4C_QUEUE_ITEM_DATA:
                connection = (Connection*)QueueDataItemGet(item);
                connection->readKey = Register(reader->selector, AIO4C_OP_READ, connection->socket, (void*)connection);
                Log(AIO4C_LOG_LEVEL_DEBUG, "managing connection %s", connection->string);
                ConnectionManagedBy(connection, AIO4C_CONNECTION_OWNER_READER);
                reader->load++;
                break;
            case AIO4C_QUEUE_ITEM_EVENT:
                connection = (Connection*)QueueEventItemGetSource(item);
                if (QueueEventItemGetEvent(item) == AIO4C_CLOSE_EVENT) {
                    if (connection->readKey != NULL) {
                        Unregister(reader->selector, connection->readKey, true, NULL);
                        connection->readKey = NULL;
                    }
                    Log(AIO4C_LOG_LEVEL_DEBUG, "close received for connection %s", connection->string);
                    reader->load--;
                    if (ConnectionNoMoreUsed(connection, AIO4C_CONNECTION_OWNER_READER)) {
                        Log(AIO4C_LOG_LEVEL_DEBUG, "freeing connection %s", connection->string);
                        FreeConnection(&connection);
                    }
                } else if (QueueEventItemGetEvent(item) == AIO4C_PENDING_CLOSE_EVENT) {
                    Log(AIO4C_LOG_LEVEL_DEBUG, "pending close received for connection %s", connection->string);
                }
                break;
            default:
                break;
        }
    }

    ProbeTimeStart(AIO4C_TIME_PROBE_IDLE);
    numConnectionsReady = Select(reader->selector);
    ProbeTimeEnd(AIO4C_TIME_PROBE_IDLE);

    if (numConnectionsReady > 0) {
        ProbeTimeStart(AIO4C_TIME_PROBE_NETWORK_READ);
        while (SelectionKeyReady(reader->selector, &key)) {
            if (SelectionKeyIsOperationSuccessful(key)) {
                connection = ConnectionRead(SelectionKeyGetAttachment(key));
            } else {
                Log(AIO4C_LOG_LEVEL_WARN, "select operation unsuccessful for connection %s", ((Connection*)SelectionKeyGetAttachment(key))->string);
            }
        }
        ProbeTimeEnd(AIO4C_TIME_PROBE_NETWORK_READ);
    }

    FreeQueueItem(&item);

    return true;
}
Ejemplo n.º 19
0
/*
 * Run task SIII
 */
int RCSchedIII(Queue ReadyQ, struct Counts *counters, struct PEs *pes) {
	int task,tmp;


	struct NodeData nd;

	int freePRR = 5;
	int freeGPP=0;
	if (IsEmpty(ReadyQ))
		return QEmpty;
	task = Front(ReadyQ);


	switch (getTaskMode(task)) {

	case HybSW:

	case SWOnly:
		/*
		 * FIXME this has to be changed to accommodate more than one GPPs
		 */
		if ((freeGPP=FindFreeGPP(0xFF,pes->SWPE))<0) {

#if SW_HW_MIG
			if (getTaskMode(task) == HybSW) {
				setTaskMode(task, HybHW);
				counters->SW2HWMig++;
#if DEBUG_PRINT
				fprintf(stderr,"Task %d migrate from SW to Any\n",task);
#endif
			} else {
#endif
				counters->busyCounterSW++;
				return BUSY;
			}

#if SW_HW_MIG
		}
#endif
		Dequeue(ReadyQ);

		nd.ExecCount = (unsigned int) dfg1[task].Emu.SWdelay;
		nd.Module = dfg1[task].TypeID;
		nd.TaskID = task;
		 setTaskSimPrrUsed(task,freeGPP+pes->HWPE->size);
		LoadProcessor(pes->SWPE->pe+freeGPP, nd);
		counters->SWTasksCounter++;
		break;

	case HybHW:
	case HWOnly:

		nd.ExecCount = (unsigned int) dfg1[task].Emu.HWdelay;
		nd.Module = dfg1[task].TypeID;
		nd.TaskID = task;

#if SW_HW_MIG
		if (TasksTypes[dfg1[task].TypeID].SWPriority == 0
				&& FindFreeGPP(0xFF,pes->SWPE)>=0
				&& getTaskMode(task) == HybHW) {
			setTaskMode(task, HybSW);
			counters->HW2SWMig++;
#if DEBUG_PRINT
			fprintf(stderr,"Task %d migrate from HW to SW highest prio \n",task);
#endif
			return EXIT_SUCCESS;
		}
#endif

		if ((tmp=SearchReuse(ReadyQ,pes->HWPE,MAX_QUEUE_TASKS))>=0)
				{task=tmp;
					nd.ExecCount = (unsigned int) dfg1[task].Emu.HWdelay;
					nd.Module = dfg1[task].TypeID;
					nd.TaskID = task;

				}


		if ((freePRR = ReusePRR_V2(nd.Module, pes->HWPE)) < 0) {
			if (IsReconfiguring()) {
				return 5;
			}
			if ((freePRR = FindFreePRRPrio(
					getTaskTypeCanRun(dfg1[task].TypeID), pes->HWPE)) < 0) {
#if SW_HW_MIG
				if (FindFreeGPP(0xFF,pes->SWPE)>=0
						&& getTaskMode(task) == HybHW) {
					setTaskMode(task, HybSW);
					counters->HW2SWMig++;
#if DEBUG_PRINT
					fprintf(stderr,"Task %d migrate from HW to SW\n",task);
#endif
					return EXIT_SUCCESS;
				} else {
#endif
					counters->busyCounterHW++;
					return BUSY;

#if SW_HW_MIG
				}
#endif
			}
#if SW_HW_MIG
			else if (TasksTypes[dfg1[task].TypeID].SWPriority <= freePRR
					&& FindFreeGPP(0xFF,pes->SWPE)>=0
					&& getTaskMode(task) == HybHW) {
				setTaskMode(task, HybSW);
				counters->HW2SWMig++;
				return EXIT_SUCCESS;
#if DEBUG_PRINT
				fprintf(stderr,"tasks [%d] moved to software due to priority \n",task);
#endif
			}
#endif
			Dequeue(ReadyQ);
			 setTaskSimPrrUsed(task,freePRR);
			 setTaskSimReused(task,NO);
			 setTaskSimConfTimeStart(task,GetTimer());

			ReconfignLoad(pes->HWPE->pe + freePRR, freePRR, ConfigTime[freePRR],
					nd);

			break;

		} else {
			counters->ReuseCounter++;
			 setTaskSimPrrUsed(task,freePRR);
			setTaskSimReused(task,YES);

			Dequeue(ReadyQ);
		}
#if DEBUG_PRINT
		fprintf(stderr,"Using PRR MATH%d for task [%d]\n",freePRR,task);
#endif

		LoadProcessor(pes->HWPE->pe + freePRR, nd);
		break;

	case CustomHW:
	case CustomHWnSW:
	default:
		fprintf(stderr,
				"ERROR [RunTask] Unsupported mode check your DFG file .. Exiting\n");
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}
Ejemplo n.º 20
0
/**
 * Segment prefetching routine
 * @param ptr		Queue that holds either segment or bucket number
 */
void * prefetch(void * ptr) {
	struct timeval a,b,c;
	gettimeofday(&a,NULL);
	Queue * q = (Queue *) ptr;
	uint64_t sid, lsid = 0, bid = 0;
	uint32_t pos, len;
	char buf[128];
	while ((sid = (uint64_t) Dequeue(q)) != 0) {
#ifdef PREFETCH_WHOLE_BUCKET
        bid = sen[sid].bucket;
        sprintf(buf, DATA_DIR "bucket/%08lx", bid);
        int fd = open(buf, O_RDONLY);
        posix_fadvise(fd, sen[sid].pos, sen[sid].len, POSIX_FADV_WILLNEED);
        close(fd);
	}
#else
		if (lsid == sid) {
			continue;
		}
		lsid = sid;
		if (bid == 0) {
			bid = sen[sid].bucket;
			pos = sen[sid].pos;
			len = sen[sid].len;
			continue;
		}
		if (sen[sid].bucket == bid && pos + len == sen[sid].pos) {
			len += sen[sid].len;
			continue;
		}

		sprintf(buf, DATA_DIR "bucket/%08lx", bid);
		int fd = open(buf, O_RDONLY);
		posix_fadvise(fd, pos, len, POSIX_FADV_WILLNEED);
		//posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
		seg_seeks++;
		if (bid != last_bid){
			b1_seeks++;
			if(bid != llast_bid){
				b2_seeks++;
				llast_bid = last_bid;
				last_bid = bid;
			}
			//fprintf(stdout,"BID: %d, size: %ld\n",last_bid,tmp_len);
		}
		/*
		if(bcache == NULL){
			BucketCache* tmp = (BucketCache*)malloc(sizeof(BucketCache));
			tmp->bid = bid;
			tmp->next=NULL;
			bcache = tmp;
		} else {
			BucketCache* tmp;
			int unique = 1;
			for(tmp=bcache;tmp!=NULL;tmp=tmp->next){
				if(tmp->bid == bid){
					unique=0;
					break;
				}
			}
			if(unique){
				tmp = (BucketCache*)malloc(sizeof(BucketCache));
				tmp->bid = bid;
				tmp->next = bcache->next;
				bcache->next = tmp;
				inf_cache_seeks++;
			}
		}
		*/
		close(fd);

		bid = sen[sid].bucket;
		pos = sen[sid].pos;
		len = sen[sid].len;
	}
Ejemplo n.º 21
0
int main(int argc, char * argv[]) {
	if (argc != 4) {
		fprintf(stderr, "Usage : %s <input file> <input chunking metafile> <instanceID>\n", argv[0]);
		return 0;
	}
	uint64_t i;

	int ifd = open(argv[1], O_RDONLY);
	int ofd = open(argv[2], O_RDONLY);
	assert(ifd != -1);
	assert(ofd != -1);

	posix_fadvise(ofd, 0, 0, POSIX_FADV_WILLNEED);
	uint64_t isize = lseek(ifd, 0, SEEK_END);
	uint64_t osize = lseek(ofd, 0, SEEK_END);
	uint64_t entries = osize / sizeof(Segment);
	uint8_t * data = MMAP_FD_RO(ifd, isize);
	Segment * base_seg = MMAP_FD_PV(ofd, osize);

	printf("Number of Segments: %d\n",entries);

	mmq = LongQueue();
	void * cdata = MMAP_MM(MAX_SEG_SIZE * LONGQUEUE_LENGTH);
	for (i = 0; i < LONGQUEUE_LENGTH; i++) {
		Enqueue(mmq, cdata + i * MAX_SEG_SIZE);
	}

	IndexService * is = GetIndexService();
	ImageService * es = GetImageService();
	CompressService * cs = GetCompressService();
	BucketService * bs = GetBucketService();


	Queue * miq = NewQueue();
	Queue * icq = NewQueue();
	Queue * ceq = NewQueue();
	Queue * ebq = NewQueue();
	Queue * bmq = NewQueue();

	is->start(miq, icq);
	cs->start(icq, ceq);
	es->start(ceq, ebq, atoi(argv[3]));
	bs->start(ebq, bmq);
	pthread_t mid;
	pthread_create(&mid, NULL, end, bmq);

	struct timeval x;
	TIMERSTART(x);

	for (i = 0; i < entries; i++) {
		Segment * seg = base_seg + i;
		seg->data = data + seg->offset;
		seg->cdata = Dequeue(mmq);
		Enqueue(miq, seg);
	}
	Enqueue(miq, NULL);

	pthread_join(mid, NULL);
	TIMERSTOP(x);
	printf("%ld.%06ld\n", x.tv_sec, x.tv_usec);

	is->stop();
	cs->stop();
	es->stop();
	bs->stop();

	free(miq);
	free(icq);
	free(ceq);
	free(ebq);
	free(bmq);

	munmap(data, isize);
	munmap(base_seg, osize);
	munmap(cdata, MAX_SEG_SIZE * LONGQUEUE_LENGTH);
	free(mmq);
	close(ifd);
	close(ofd);

	return 0;
}
Ejemplo n.º 22
0
int TopologicalSort(struct Graph * G, int ** sorted)
{
  /*
    Perform a topological sort on graph G, creating
    an array of G->NumVertices integers and returning
    it in *sorted.

    Returns 0 on success,
    <0 on error (GRAPH_BADPARAM, GRAPH_OUTOFMEM, GRAPH_BADGRAPH)
  */
	
  int first, last, i;
  int * queue;
  int * itable;
  struct EdgeScan E;

  if (!G || !sorted) return GRAPH_BADPARAM;

  queue=malloc(sizeof(int)*G->NumVertices);
  itable=malloc(sizeof(int)*G->NumVertices);
  if (!queue || !itable)
  {
    free(queue);free(itable);
    return GRAPH_OUTOFMEM;
  }

  InitIndegreeTable(G,itable);
  last=0;first=0;

  /* search for vertices with indegree 0 */
  for (i=0;i<G->NumVertices;i++) 
  {
    if (itable[i]==0) Enqueue(i);
  }

  /* while there are still vertices with indegree 0... */
  while (last!=first)						
  {
    Dequeue(i);
    EdgeScanStart(G,i,&E);
    while (EdgeScanNext(&E)==0)			
    {
      /* decrement the indegree of vertices adjacent to them */
      
      itable[E.Dest]--;
      if (itable[E.Dest]==0) Enqueue(E.Dest);
    }
    EdgeScanEnd(&E);
  }

  free(itable);

  /* if we haven't dequeued G->NumVertices elements, we have a cyclic graph */
  if (first!=G->NumVertices)				
  {
    free(queue);
    return GRAPH_BADGRAPH;
  }

  *sorted=queue;
  return 0;
}
Ejemplo n.º 23
0
int main()
{
  printf("############ WELCOME TO QUEUE OPERATIONS ############# \n \n");
  int i=0;
  int size=0,data=0;
  queue *Q=(queue *)malloc(sizeof(queue));
  while(1)
  {
  printf("\n 1)Create a Queue(Press 1)\n 2)Insert an element(Press 2)\n 3)Delete an element(Press 3)\n 4)Show the Queue(Press 4)\n 5)Delete a Queue(Press 5)\n 6)Show Queue Size(Press 6)\n 7)Exit(Press 7 to exit) \n");
  scanf("%d",&i);
  switch(i)
  {
    case 1:

        printf("\nEnter the size of the stack= ");
        scanf("%d",&size);
       *CreateQueue(Q,size);
       printf("Enter the values of the element (Press -1  to stop)= \n");
       while(1)
       {

          scanf("%d",&data);
          if(data==-1)
              break;
          else
              Enqueue(Q,data);
       };
       break;

    case 2:
          printf("\nEnter the value of the element= ");
          scanf("%d",&data);
          if(data==-1)
              break;
          else
              Enqueue(Q,data);
        break;

    case 3:
          printf("The element deleted is =%d\n",Dequeue(Q));
          break;
    case 4:
       if (flag==1)
       {
        if(!isEmptyQueue(Q))
        {
          printf("\nThe elements of the Queue are: ");
          for(i=Q->head;i<=Q->tail;i++)
            printf("%d ",Q->array[i]);
          printf("\n");
        }
        else
            printf("Queue is empty !!!! \n");
       }
      else
        printf("There is no Queue !!! \n");
          break;
    case 5:
          DeleteQueue(Q);
          printf("Queue is deleted !!! \n");
          break;
    case 6:
          printf("The Queue size is = %d\n",Queuesize(Q));
          break;
    case 7:
          exit(0);
    default:
          printf("Invalid option \n");
          break;
   }
  }

 return 0;
}