Example #1
0
int Wireless_Init(Skaro_Wireless * w){
	w->send_in_progress = 0;
	w->receive_in_progress = 0;
	w->read_array_position = 0;
	QueueInit(&(w->write_queue), (void *)w->write_data, WRITE_QUEUE_SIZE);
	QueueInit(&(w->read_queue), (void *)w->read_data, READ_QUEUE_SIZE);
	return 1;
}
Example #2
0
///////////////////////////////////////////////////////////////////////////////
// ReqMgrInit
// 
// Description:
//	Initializes the request manager for use.
// 
// Inputs:
//	pReqMgr			- Pointer to a request manager.
//	pfnGetCount		- Pointer to a callback function invoked to 
//					get the number of available objects.
//	GetContext		- Context to pass into the pfnGetCount function.
//
// Outputs:
//	None.
// 
// Returns:
//	FSUCCESS				- the request manager was successfully initialized.
//	FINSUFFICIENT_MEMORY	- there was not enough memory to initialize the
//							request manager.
// 
///////////////////////////////////////////////////////////////////////////////
FSTATUS
ReqMgrInit(
	IN REQ_MGR* const pReqMgr,
	IN REQMGR_GET_COUNT_FUNC pfnGetCount,
	IN void* const GetContext )
{
	FSTATUS		Status;

	ASSERT( pReqMgr );
	ASSERT( pfnGetCount );

	// Initialize the state of the request manager, in case it hasn't yet 
	// been done.
	ReqMgrInitState( pReqMgr );

	if( !QueueInit( &pReqMgr->m_RequestQueue, 1 ) )
		return( FINSUFFICIENT_MEMORY );

	Status = GrowPoolInit( &pReqMgr->m_RequestPool, REQ_MGR_START_SIZE, 
		sizeof(REQUEST_OBJECT), REQ_MGR_GROW_SIZE, NULL, NULL, NULL, NULL );

	if( Status != FSUCCESS )
		return( Status );

	// Store callback information for the count function.
	pReqMgr->m_pfnGetCount = pfnGetCount;
	pReqMgr->m_GetContext = GetContext;

	pReqMgr->m_Initialized = TRUE;

	return( FSUCCESS );
}
Example #3
0
//
//  Function:       _InitModem
//
//  Description:    Initialization of Radio Modem
//
//  Return Values:
//
//  Name        Explanation
//  ----------- -------------------------------------------------------------------
//  RetStatus    Error code
//
int _InitModem( t_boolean FirstTime )
{
  int       RetStatus     = RM_SUCCESS;
  time_t      ltime;

  HeapBuffDef *pHeap      = Data_GetHeapPtr();
  pHeap->DataLength      = 0;           //Initialization of Main Heap Buffer

  RM_InitPrint( "ErrorRM.txt" ); //I need to put here fileName of error log file

  time( &ltime );
  PrintLogMessage( "[I] Initialization started at: ", ctime( &ltime ), 0 );

  //Initialization of internal memory manager
  if ( (RetStatus = Mem_Init( FirstTime )) != RM_SUCCESS )
    PrintError( "[E] InitModem ( Memory Error )", "RetStatus:", RetStatus ); 

  //Initialization of internal queues
  QueueInit(FirstTime); 

#ifdef RM_STANDALONE
  Uart_Init();
#endif

  if ( (RetStatus = VRM_Init(UNCONFIRMED)) == RM_SUCCESS )
    PrintError( "InitModem: COMPLETED", "", 0 ); 
  else
  {
    PrintError( "InitModem: FATAL ERROR", "Power cycle your modem. RetStatus:", RetStatus ); 
  }//end else

  return( RetStatus );
}//RM_InitModem
Example #4
0
void Cqtestbench(void)	// queue Test bench
{
unsigned char data;
unsigned char status;

	QueueInit();	// initialize queue
	
status=	PushQueue(1);	// Push something into the queue
status=	PushQueue(2);
status=	PushQueue(3);
	
	if(PushQueue(4)==QFULL)
	{
		_printf( "Queue Overflowed \n");
		return;
	}


	while (QueueStatus())		// some news?
	{
	status=PullQueue(&data); 	// if yes then get data from queue
		_printf( "Data pulled: %d , Remaining: %d   \n",data,QueueStatus());
	}

}
void main()
{
    queue s;
    int i,j,k,m;
    QueueInit(&s);
    while(1)
    {
        printf("*****请选择操作*****\n");
        printf("1、入队  2、出队  3、取队头元素  4、遍历队列  5、退出\n");
        printf("选择:\n");
        scanf("%d",&i);
        switch(i)
        {
        case 1:
            printf("输入要入队的个数:\n");
            scanf("%d",&m);
            printf("输入%d个元素的值:\n",m);
            for(i=0; i<m; i++)
            {
                scanf("%d",&j);
                QueuePush(&s,j);
            }
            break;
        case 2:
            printf("输入要出队的个数:\n");
            scanf("%d",&i);
            printf("出队的元素为:\n");
            for(; i>0; i--)
            {
                k=QueuePop(&s,&j);
                if(k)
                    printf("%d ",j);
                else
                {
                    printf("该队没有足够的元素\n");
                    break;
                }
            }
            break;
        case 3:
            i=Getfront(&s);
            if(i!=0)
                printf("队头元素为%d\n",i);
            else
                printf("该队列没有元素!\n");
            break;
        case 4:
            QueueTrav(s);
            break;
        case 5:
            break;
        default:
            printf("您的输入有误\n");
        }
        system("pause");
        system("cls");
    }

}
Example #6
0
int main(void) {
    Queue  que;
    char op[5];
                
    QueueInit(&que); /* キューの初期化 */
    //キューの中身を確認
    if(!QueueIsEmpty(&que)){
        printf("初期化失敗\n");
        return (-1);
    }

    while (1) {
        int  m, no;
        char name[NAMELEN];
        Node *data;

        printf("Operation:");
        printf("(1)データの追加(enqueue),(2)データの削除(dequeue), (0) 終了:");
        scanf("%s", op);

        m=atoi(op);

        if (m == 0)
            break;

        switch(m) {
            case 1: data = AllocNode();
                printf("追加するデータを入力してください。\n");
                printf("番号:");scanf("%d", &no);
                printf("名前:");scanf("%s", name);
                SetNode(data,no,name,NULL);
                QueueEnque(&que, data);

                //キューの中身を確認
                if(QueueIsEmpty(&que)){
                    printf("エンキュー失敗\n");
                    return (-1);
                }
                break;    
            case 2: if(data = QueueDeque(&que)) {
                        puts("デキューしたデータ:");
                        printf("番号:%d,名前:%s\n", data->no, data->name);
 //                           free(data);
                        }
                    else {
                        puts("デキューできません。");
                    }
                    break;
        }
        printf("キューの一覧<%d>:\n", QueueNo(&que));
        PrintQueue(&que);
    }

    QueueFree(&que);

    return(0);

}
Example #7
0
void SerialInit2(void)
{
  serialErrors2 = SERIAL_NO_ERROR; /* reset the error status */
  QueueInit(&serialTxQueue2); /* initialize the Tx Queue */
  QueueInit(&serialRxQueue2); /* initialize the Rx Queue */

  
  /* configure I/O pins as follows: */
  ANSEL18 = 0;/* RG2 is digital     */
  TRISG2 = 1; /* RX pin is an input */
  TRISG1 = 0; /* TX pin is an output */
  
  /* configure TXSTA2 as follows: */
  BRGH2 = 1;  /* high speed baud rate */
  SYNC2 = 0;  /* Asynchronous mode */
  TX92 = 0;   /* Select 8-bit transmission */
  
  /* configure RCSTA2 as follows: */
  CREN2 = 1;  /* Enable receiver */
  RX92 = 0;   /* select 8-bit reception */
  SPEN2 = 1;  /* serial port is enabled */
  
  /* configure BAUDCON1 as follows: */
  ABDEN2 = 0; /* Disable Baud Rate Measurement */
  WUE2   = 0; /* RX2 pin not monitored for Auto-Wake-Up */
  BRG162 = 0; /* 8-bit Baud Rate Generator */
  
  /* Calculating baud rate:
     Desired Baud Rate = Fosc/[16*(N+1)]
     N = Fosc/[16*{Desired Baud Rate}] - 1
     N = 18.432M/[16*115.2K] - 1
     N = 9
     N = 0x09
     
     Error = 0%
   */
  SPBRGH2 = 0; /* high byte of N */
  SPBRG2 = 9;  /* low byte of N */
  
  /* configure interrupts */
  TX2IE = 0;  /* interrupt driven transmitter with kickstarting */  
  TXEN2 = 1;  /* Transmit is enabled; this sets TX2IF */
  RC2IF = 0;
  RC2IE = 1;  /* interrupt driven receiver */
}
Example #8
0
int main(void)
{
    DDRA = 0xFF;
    DDRB = 0xBF; PORTB = 0x40;
    DDRC = 0xFF;
    DDRD = 0x8F; PORTD = 0x70;
    
    lcd_command_queue = QueueInit(10);
    sound_command_queue = QueueInit(10);
    lock_command_queue = QueueInit(10);
    
    task_monitor_lock.elapsedTime = 200;
    task_monitor_lock.period = 200;
    task_monitor_lock.state = st_lock_monitor_start;
    task_monitor_lock.TickFct = &lock_monitor_tick;
    
    task_lock_control.elapsedTime = 250;
    task_lock_control.period = 250;
    task_lock_control.state = st_lock_start;
    task_lock_control.TickFct = &lock_controller_tick;
    
    task_main.elapsedTime = 100;
    task_main.period = 100;
    task_main.state = st_main_start;
    task_main.TickFct = &main_controller_tick;
    
    task_sound.elapsedTime = 100;
    task_sound.period = 100;
    task_sound.state = st_sound_start;
    task_sound.TickFct = &sound_tick;
    
    task_lcd.elapsedTime = 100;
    task_lcd.period = 100;
    task_lcd.state = st_lcd_start;
    task_lcd.TickFct = &lcd_tick;
    
    A2D_init();
    TimerSet(tasksPeriodGCD);
    TimerOn();
    
    while(1)
    {
        ;
    }
}
//----------------------------------------------------------------------
//
//	ProcessModuleInit
//
//	Initialize the process module.  This involves initializing all
//	of the process control blocks to appropriate values (ie, free
//	and available).  We also need to initialize all of the queues.
//
//----------------------------------------------------------------------
void
ProcessModuleInit ()
{
  int		i;

  dbprintf ('p', "Entering ProcessModuleInit\n");
  QueueInit (&freepcbs);
  QueueInit (&runQueue);
  QueueInit (&waitQueue);
  QueueInit (&zombieQueue);
  for (i = 0; i < PROCESS_MAX_PROCS; i++) {
    dbprintf ('p', "Initializing PCB %d @ 0x%x.\n", i, &(pcbs[i]));
    pcbs[i].flags = PROCESS_STATUS_FREE;
    QueueLinkInit (&(pcbs[i].l), (void *)&pcbs[i]);
    QueueInsertFirst(&freepcbs, &(pcbs[i].l));
  }
  currentPCB = NULL;
  dbprintf ('p', "Leaving ProcessModuleInit\n");
}
Example #10
0
static NDIS_STATUS
VenetSetupAdapter(PADAPTER a)
{

    NDIS_STATUS			rc;
    NDIS_TIMER_CHARACTERISTICS	timer;

    a->lookAhead = NIC_MAX_LOOKAHEAD;
    a->numTcbs = NIC_MAX_BUSY_SENDS;
    a->refCount = 1;
    VENET_SET_FLAG(a, VNET_DISCONNECTED);

    QueueInit(&a->sendQueue);

    NdisInitializeListHead(&a->recvFreeList);
    NdisInitializeListHead(&a->recvToProcess);
    NdisInitializeListHead(&a->tcbFree);
    NdisInitializeListHead(&a->tcbBusy);

    NdisAllocateSpinLock(&a->lock);
    NdisAllocateSpinLock(&a->recvLock);
    NdisAllocateSpinLock(&a->sendLock);

    NdisInitializeEvent(&a->removeEvent);
    NdisInitializeEvent(&a->sendEvent);


    /* We use the opposite sense of the sendEvent,
     * SET == No Tx in use
     * UNSET == Tx in use
     */
    NdisInitializeEvent(&a->sendEvent);
    NdisSetEvent(&a->sendEvent);

    /* Create Rest and receive timers. */
    NdisZeroMemory(&timer, sizeof(NDIS_TIMER_CHARACTERISTICS));
    timer.Header.Type = NDIS_OBJECT_TYPE_TIMER_CHARACTERISTICS;
    timer.Header.Revision = NDIS_TIMER_CHARACTERISTICS_REVISION_1;
    timer.Header.Size = sizeof(NDIS_TIMER_CHARACTERISTICS);
    timer.AllocationTag = VNET;
    timer.TimerFunction = VenetResetTimerDpc;
    timer.FunctionContext = a;

    rc = NdisAllocateTimerObject(a->adapterHandle, &timer, &a->resetTimer);
    if (rc != NDIS_STATUS_SUCCESS)
        goto done;

    timer.TimerFunction = VenetReceiveTimerDpc;
    rc = NdisAllocateTimerObject(a->adapterHandle, &timer, &a->recvTimer);
    if (rc != NDIS_STATUS_SUCCESS)
        goto done;

done:
    return rc;
}
Example #11
0
tQueueHandle lw_QueueCreate (uint16_t uQueueLength, uint16_t ItemSize)
{
    tQueueHeader *pQueue;
    uint8_t *pData;
     
    pQueue = malloc (sizeof (tQueueHeader) + sizeof (uQueueLength * ItemSize));
    pData = pQueue + 1;

    QueueInit (pQueue, pData, uQueueLength, ItemSize);

    return pQueue;
}
Example #12
0
/*****************************************************************************
 * Create: allocates adjust video thread output method
 *****************************************************************************
 * This function allocates and initializes a adjust vout method.
 *****************************************************************************/
static int Create( vlc_object_t *p_this )
{
    filter_t *p_filter = (filter_t *)p_this;
    filter_sys_t *p_sys;

    /* Allocate structure */
    p_filter->p_sys = malloc( sizeof( filter_sys_t ) );
    if( p_filter->p_sys == NULL )
        return VLC_ENOMEM;
    p_sys = p_filter->p_sys;

    BufferInit( &p_sys->input );
    BufferInit( &p_sys->output );
    QueueInit( &p_sys->atomic );
    QueueInit( &p_sys->pending );
    QueueInit( &p_sys->processed );
    do_ListInit( &p_sys->overlays );

    p_sys->i_inputfd = -1;
    p_sys->i_outputfd = -1;
    p_sys->b_updated = true;
    p_sys->b_atomic = false;
    vlc_mutex_init( &p_sys->lock );

    p_filter->pf_sub_source = Filter;

    config_ChainParse( p_filter, "overlay-", ppsz_filter_options,
                       p_filter->p_cfg );

    p_sys->psz_inputfile = var_CreateGetStringCommand( p_filter,
                                                       "overlay-input" );
    p_sys->psz_outputfile = var_CreateGetStringCommand( p_filter,
                                                        "overlay-output" );

    var_AddCallback( p_filter, "overlay-input", AdjustCallback, p_sys );
    var_AddCallback( p_filter, "overlay-output", AdjustCallback, p_sys );

    RegisterCommand( p_filter );
    return VLC_SUCCESS;
}
Example #13
0
static void QueueEmpty( DirEntryQueue *queue )
/********************************************/
{
    QueueNode   *curr;
    QueueNode   *next;

    for( curr = queue->front; curr != NULL; curr = next ) {
        next = curr->next;
        RCFREE( curr );
    }

    QueueInit( queue );
} /* QueueEmpty */
Example #14
0
int main(void)
{
  board_init();
  system_init();
  QueueInit(&lock_fifo);
  //modbus485有线的配置
  eMBInit(MB_RTU, MSlaveID, MODBUS_UART_NUMBER, MODBUS_UART_BAUDRATE, MB_PAR_NONE); 
  eMBEnable();
  while (1) {
    
    if(Timer2_Get_Sensor_Data() == 0){
      QueueInit(&lock_fifo);
      if(Door_Flag1 == 1)
    {
        SetAndSendRemoteOpenDoorCmd();
        
        Door_Flag1 = 0;
    }      
    }
    
  }
}
Example #15
0
void CheckForExpressions(char** in) {
    Queue queue;

    char RegExp[] = {'|', '&', '$', '~'};

    char* line = *in;
    char* temp;

    int i;
    int NumExps = strlen(RegExp);

    char c;
    char exp;

    QueueInit(&queue);

    while (*line == ' ') {
        ++line;
    }

    c = *line;

    while (c) {
        exp = 0;
        if (c == ' ' && *(line + 1) == ' ') {
            ++line;
        } else {
            for (i = 0; i < NumExps; ++i) {
                if (c == RegExp[i]) {
                    if ( *(line - 1) != ' ' )
                        Push(&queue, ' ');
                    Push(&queue, c);
                    Push(&queue, ' ');
                    exp = 1;
                    break;
                }
            }

            if (!exp) {
                Push(&queue, c);
            }

            ++line;
        }
        c = *line;
    }
    free(*in);
    *in = queue.data;
}
Example #16
0
static void QueueEmpty( DirEntryQueue * queue )
/*********************************************/
{
    QueueNode * curr;
    QueueNode * old;

    curr = queue->front;
    while( curr != NULL ) {
        old = curr;
        curr = curr->next;
        RcMemFree( old );
    }

    QueueInit( queue );
} /* QueueEmpty */
Example #17
0
void InitHallSensorProc()
{
	//bind to message queue
	//hard coded until further notice
	Bind(HSMQNUM);//defined in MQNumENum.h

	//wait for synchronization start from keyboardProc
	char dummyBlock[1];
	int syncSrc = KBMQNUM;
	Recv(&syncSrc, HSMQNUM, dummyBlock, 1);

	//create queue for keeping track of hall sensor interrupt triggers
	//it only needs to hold one flag
	int HSQueueID = QueueInit(HSQUEUEBLOCKNUMBER, sizeof(char));

	char flag[1];
	flag[0] = 0;

	//Reset hall sensors to initialize them
	Send(HSMQNUM, ATMELMQNUM, flag, sizeof(char));

	//recv acknowledge that it worked
	int src = ATMELMQNUM;
	Recv(&src, HSMQNUM, flag, sizeof(char));

	//Init interrupts on portF which will trigger when a hall sensor is triggered
	PORTF_Init(HSQueueID);

	//polling loop to see if there are any interrupts
	while(true)
	{
		if(Dequeue(HSQueueID, (void*)flag))
		{
			//flag will either have a '1' which means atmel 1 needs to be polled (HS 1-8)
			//or a '3' which means atmel 3 needs to be polled (HS 9-32)

			//send which atmel to poll to Atmelproc
			Send(HSMQNUM, ATMELMQNUM, flag, sizeof(char));
		}
		else
		{
			//it would be cool to add a forced context switch to next process so time isn't wasted here
			//or, rather, the smartest option be to have no queue and to immediately from within the isr send a message to the Atmel Comm process
		}
	}
}
Example #18
0
/** Code to test this Queue implementation
This code is only included for example purposes and to ensure that 
this implementation works in all situations

This code at present is not exhaustive.

STEPS:
- Test 1
  -# Push some integers onto the Queue inplace of pointers.
  -# Pop all of the elements off the queue to make sure that they match
- Test2 
  -# TODO 

\todo Write a more exhaustive test 

*/
int QueueTest()
{
	Queue queue;
	void* ary[10];

	QueueInit( &queue, ary, 10 );

	// Test 1
	{
		{
			int i;
			for( i = 0 ; i < 10 ; i++ )
				QueuePush( &queue, (void*) i ); 
		}

		if(QueueIsFull(&queue) != TRUE)
			return 1;

		{
			int i;
			for( i = 0 ; i < 10 ; i++ )
			{
				int val = (int) QueuePop( &queue );
				if(val != i)
					return 2;
			}		
		}
		
		if(QueueIsEmpty(&queue) != TRUE)
			return 3;

		if(QueueIsFull(&queue) != FALSE)
			return 4;
	}


	// Test 2
	{
		QueuePush( &queue, (void*) 1234); 
		if((int)QueueFront(&queue) != 1234)
			return 5;
	}


	return 0;
}
Example #19
0
File: main.c Project: z9u2k/remote
/**
 * update LED status
 */
void BlinkUSBStatus(void) {

    #define BLINK_COUNT (0xffff/16)

    static UINT16 led_count = 0xffff;
    static USB_DEVICE_STATE lastState = DETACHED_STATE;
    static BOOL blinkConfiguredSequence = FALSE;

    led_count++;
    
    if (USBSuspendControl == 1) {
        LED_Off();
    } else {
        if (USBGetDeviceState() < CONFIGURED_STATE) {
            if (blinkConfiguredSequence) {
                blinkConfiguredSequence = FALSE;
            }

            if (lastState == CONFIGURED_STATE) {
                ReceiverOff();
            }

            if (led_count == 0) {
                LED_On();
            } else if (led_count == BLINK_COUNT) {
                LED_Off();
            }
        } else {
            if (lastState != CONFIGURED_STATE) {
                QueueInit();
                ReceiverOn();
                LED_On();
                blinkConfiguredSequence = TRUE;
                led_count = 0;
            } else if (blinkConfiguredSequence && led_count == 0) {
                blinkConfiguredSequence = FALSE;
                LED_Off();
            }
        }
    }

    lastState = USBGetDeviceState();
}
///////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
///////////////////////////////////////////////////////////////////////////
OSCL_EXPORT_REF ThreadSafeCallbackAO::ThreadSafeCallbackAO(void *aObserver, uint32 aDepth, const char *aAOname, int32 aPriority)
        : OsclActiveObject(aPriority, aAOname),
        iLogger(NULL)
{


    OsclReturnCode queue_init_status = OsclSuccess;
    OsclProcStatus::eOsclProcError mutex_init_status = OsclProcStatus::SUCCESS_ERROR;
    OsclProcStatus::eOsclProcError sema_init_status = OsclProcStatus::SUCCESS_ERROR;
    int32 err = 0;

    iLoggerString = aAOname;
    iObserver = aObserver;
    Q = NULL;

    OSCL_TRY(err,
             queue_init_status = QueueInit(aDepth);	//create the Q
             mutex_init_status = Mutex.Create(); // Create Mutex
             sema_init_status  = RemoteThreadCtrlSema.Create(aDepth);

             ThreadLogon(); // add to scheduler
            );
void findSSShortestPath(graphT g, int v, int **distance) {
// int* findSSShortestPath(graphT g, int v) {
    queueT queue = QueueInit(n);
    // GraphPrint(g);
    // int* distance = malloc(sizeof(int) * n);
    int* parent = malloc(sizeof(int) * n);
    for (int i = 0; i < n; ++i) {
        // distance[i] = INT_MAX;
        (*distance)[i] = INT_MAX;
        parent[i] = UNDEFINED;
    }
    // distance[v] = 0;
    (*distance)[v] = 0;
    // printArray(distance, n);
    QueueEnqueue(queue, v);
    // printf("Enqueued %d\n", v);
    while (!QueueIsEmpty(queue)){
        int t = QueueDequeue(queue);
        // printf("Dequeued %d\n", t);
        // printf("Neighbor of %d: \n", t);
        for (int i = 0; i < GraphOutDegreeForVertex(g, t); ++i) {
            int w = g->alist[t]->list[i];
            // printf("    %d\n", w);
            if ((*distance)[w] == INT_MAX){
            // if (distance[w] == INT_MAX){
                parent[w] = t;
                // distance[w] = distance[t] + 1;
                (*distance)[w] = (*distance)[t] + 1;
                QueueEnqueue(queue, w);
                // printf("Enqueued %d\n", w);
            }
        }
    }
    // printArray(distance, n);
    QueueDestroy(queue);
    free(parent);
}
Example #22
0
/***********************7。图的广度周游**********************/
void BFS(GRAPH g, int v, int mark[])
//从v出发广度优先周游图g中能访问的各个顶点
{
	int v1, v2;
	SEQQUEUE q;
	QueueInit(&q);
	QueueIn(&q, v);
	mark[v] = 1;
	printf("%c   ", g.vexs[v]);
	while (QueueIsEmpty(q) == 0)
	{
		QueueFront(q, &v1);
		QueueOut(&q);
		for (v2 = 0; v2 < g.num; v2++)
		{
			if (g.arcs[v1][v2] != 0 && mark[v2] == 0)
			{
				QueueIn(&q, v2);
				mark[v2] = 1;
				printf("%c   ", g.vexs[v2]);
			}
		}
	}
}
Example #23
0
void markPoit(int myMaze[][9], stack* s, Postion end) {
	Postion* p = stack_pop(s);
	Queue* q = QueueInit();
	Postion current = end;
	while(p != 0) {
		if (isNear(*p, current) == 1) {
			myMaze[p->y][p->x] = 1;
			current = *p;
			QueueAdd(q, p);
		} else {
			tk_free(p);
		}
		p = stack_pop(s);
	}
	p = QueueGet(q);
	printf("(5,5)");
	while(p != 0) {
		printf("<-(%d,%d)", p->x, p->y);
		tk_free(p);
		p = QueueGet(q);
	}
	printf("\n");
	QueueDestory(q);
}
Example #24
0
static void system_init(void) 
{



  _asm sei; 

  #ifdef FLASH     

 /////    pll_init();	  // solo para flash  (ver config.h)

  #endif				     
                           
    QueueInit();
    Sci_Init();


    PORTA = 0x00;
    DDRA = 0xFF;
    
    init_SPI();
    
    atd_init();
    
    rti_start();      

                 
    speed=DEFAULT_SPEED;   // message shift speed
    Led_intensity=DEFAULT_INTENSITY;
 
    
//    rti_init();

  _asm cli; 

}
Example #25
0
void UART1_TxQueueInit(U16 length)
{
    QueueInit(&UART1TxQueue, length);
}
Example #26
0
int
main( int ac, char *av[] )
{
	pthread_t	th[5];
	int	i;
	M_t	*pM;
	int	Ret;
	void	*pRet;

	QueueInit( &Queue );

	/* 1. timeout */
	printf("### 1. 0s timed_wait timeout ###\n");
	pthread_create( &th[0], NULL, ThreadWait, (void*)0 );

	pRet = NULL;
	pthread_join( th[0], &pRet );
	ASSERT( (int)(intptr_t)(pRet) == ETIMEDOUT );

	/* 2. timeout */
	printf("### 2. 10s timed_wait timeout ###\n");
	pthread_create( &th[0], NULL, ThreadWait, (void*)(10*1000) );

	pRet = NULL;
	pthread_join( th[0], &pRet );
	ASSERT( (int)(intptr_t)(pRet) == ETIMEDOUT );

	/* 3. timeout */
	printf("### 3. 10s timed_wait receive and timeout###\n");
	pthread_create( &th[0], NULL, ThreadWait, (void*)(10*1000) );

	pM = M_Create( 3 );
	Ret = QueuePostEntry( &Queue, pM, m_Lnk );
	if( Ret < 0 )	goto err;

	pRet = NULL;
	pthread_join( th[0], &pRet );
	ASSERT( (int)(intptr_t)(pRet) == ETIMEDOUT );

	/* 4. one for-ever-wait thread */
	printf("### 4. one for_ever_wait thread ###\n");
	pthread_create( &th[0], NULL, ThreadWait, (void*)FOREVER );

	pM = M_Create( 4 );
	Ret = QueuePostEntry( &Queue, pM, m_Lnk );
	if( Ret < 0 )	goto err;

	sleep( 1 );

	/* 5. multi for-ever-wait threads */
	printf("### 5. multi for_ever_wait threads ###\n");
	pthread_create( &th[1], NULL, ThreadWait, (void*)FOREVER );
	pthread_create( &th[2], NULL, ThreadWait, (void*)FOREVER );
	pthread_create( &th[3], NULL, ThreadWait, (void*)FOREVER );
	pthread_create( &th[4], NULL, ThreadWait, (void*)FOREVER );

	pM = M_Create( 5 );
	Ret = QueuePostEntry( &Queue, pM, m_Lnk );
	if( Ret < 0 )	goto err;

	sleep( 1 );

	/* 6. suspend/resume */
	printf("### 6. suspend / count / resume###\n");
	QueueSuspend( &Queue );

	QueueMax(&Queue, 1 );
	pM = M_Create( 6 );
	Ret = QueuePostEntry( &Queue, pM, m_Lnk );
	printf("Posted to suspended Queue Ret=%d Cnt=%d Omitted=%d\n", 
				Ret, QueueCnt(&Queue), QueueOmitted(&Queue));
	pM = M_Create( 61 );
	Ret = QueuePostEntry( &Queue, pM, m_Lnk );
	printf("Posted to suspended Queue Ret=%d Cnt=%d Omitted=%d\n", 
				Ret, QueueCnt(&Queue), QueueOmitted(&Queue));
	pM = M_Create( 62 );
	Ret = QueuePostEntry( &Queue, pM, m_Lnk );
	printf("Posted to suspended Queue Ret=%d Cnt=%d Omitted=%d\n", 
				Ret, QueueCnt(&Queue), QueueOmitted(&Queue));
	sleep( 1 );
	printf("q_cnt=%d\n", QueueCnt( &Queue ) );

	printf("Resume Queue\n");
	QueueResume( &Queue );
	sleep( 1 );

	/* 7. Abort */
	printf("### 7. Abort ###\n");
	QueueAbort( &Queue, 9 );
	sleep( 10 );

	for( i = 0; i < 5; i++ ) {
		pRet = NULL;
		pthread_join( th[i], &pRet );
		ASSERT( (int)(intptr_t)(pRet) == SIGKILL );
	}

	QueueDestroy( &Queue );

	printf("=== OK ===\n");
	return( 0 );
err:
	printf("=== NG ===\n");
	return( -1 );
}
Example #27
0
//****************************************************************
// main
//****************************************************************
int main(int argc, char *argv[]) 
{
    int i, roadid[4], opt;
    pthread_t arrv_tid, road_tid[4];
    for (i=0; i<4; i++) 
	{
		QueueInit(&Q[i]); 
		roadid[i]=i; 
		Sem437Init(&Barrier[i],0);
	}

    for (i=0; i<3; i++) 
	{
		turn[i].num=turn[i].waitsum=turn[i].waitmax=0;
	}
    
	vClk = SetVClk(7,0,0); // start at 07:00:00
    srand(getpid()); 
	InitTime(); // real clock, starting from 0 sec
    Sem437Init(&RedLight, 1); 

    while((opt=getopt(argc,argv,"hT:A:Q:X:")) != -1) switch(opt) 
	{
    	case 'h':
        	printf("command -T simulation time in sec -A arrival rate\
					per 10 sec -Q max queue len\n");
        	break;
      	case 'T': timers=atoi(optarg)/10;
        	break;
      	case 'A': mean = atof(optarg);
        	printf("mean arrival: mean=%02f \n", mean);
        	break;
	    case 'Q': MAXQLEN=atoi(optarg);
        	if (MAXQLEN>200 || MAXQLEN<0) 
				MAXQLEN = 20; //set backe to default
        	printf("Max Queue lwngth: MAXQLEN=%d \n", MAXQLEN);
        	break;
      case 'X': time2pass=atoi(optarg);
       		printf("Time to pass the intersaction: time2pass secs =%d \n", time2pass);
        	break;
      default:
        	fprintf(stderr, "Err: no such option:`%c'\n",optopt);
     }

    // simulate 1 hour (60 minutes), between 7:00am-8:00am
    printf("Simulating mean arrival %f/10s time to pass %ds sim duration %ds\n",
																mean, time2pass, timers*10);
    // thread, taking care of arriving
    if (pthread_create(&arrv_tid,NULL,CarArrive, NULL)) 
	{
      	fprintf(stderr, "Error in thread creating\n");
    	return(1);
    }
    for (i=0; i<4; i++) 
	{
    	if (pthread_create(&road_tid[i],NULL,CarDispatch, &roadid[i])) 
		{
        	fprintf(stderr, "Error in thread creating\n");
          	return(1);
       	}
	}
    // let simulation run for timers' duration
    if (pthread_join(arrv_tid, NULL)) 	
	{
    	fprintf(stderr, "Error in thread joining\n");
       	return(1);
    }
    for (i=0; i<4; i++) 
	{
    	if (pthread_join(road_tid[i],NULL)) 
		{
        	fprintf(stderr, "Error in thread joining\n");
          	return(1);
       	}
	}
    
	nResidue = Q[0].len + Q[1].len + Q[2].len + Q[3].len;
    // Print Turn statistics
    char turnstr[4][15] = {"Go Straight","Turn Left  ","Turn Right ","U Turn     "};

    for (i=0; i<4; i++) 
		if (turn[i].num>0) 
			printf("%s: num %d max %d avg %d\n",
				turnstr[i], turn[i].num,turn[i].waitmax,turn[i].waitsum/turn[i].num);
    
	printf("Finishing arrival %d passing %d detouring %d remaining %d %d\n",
			nArrv, nPass, nDetour, nResidue,nPass+nDetour+nResidue);
    // Print Road Queue statistics
    char roadstr[4][15] = {"E:East ","S:South","W:West ","N:North"};
    
	for (i=0; i<4; i++) 
		if (road[i].num>0) 
			printf("%s: num %d max %d avg %d\n",
				roadstr[i], road[i].num,road[i].waitmax,road[i].waitsum/road[i].num);
}
Example #28
0
/*
 * Thread - Compose ArchReqs in the queue.
 */
void *
Compose(
	void *arg)
{
	QueueInit(&composeQ);
	ThreadsInitWait(wakeup, wakeup);

	while (AdState->AdExec < ES_term) {
		struct QueueEntry *qe;
		struct ArchReq *ar;
		struct ArchSet *as;

		/*
		 * Wait for entries in the queue.
		 */
		ThreadsReconfigSync(RC_allow);
		PthreadMutexLock(&composeWaitMutex);
		while (AdState->AdExec < ES_term &&
		    composeQ.QuHead.QeFwd == &composeQ.QuHead) {
			PthreadCondWait(&composeWait, &composeWaitMutex);
		}
		if (AdState->AdExec >= ES_term) {
			PthreadMutexUnlock(&composeWaitMutex);
			break;
		}
		ThreadsReconfigSync(RC_wait);

		/*
		 * Remove and process next compose queue entry.
		 */
		qe = composeQ.QuHead.QeFwd;
		ar = qe->QeAr;
		arname = qe->QeArname;
		QueueRemove(qe);
		PthreadMutexUnlock(&composeWaitMutex);

		arFiList = NULL;
		if ((ar->ArStatus & (ARF_changed | ARF_merge | ARF_rmreq)) ||
		    (ar->ArFlags & AR_unqueue)) {
			ar->ArFlags &= AR_unqueue;
			MessageReturnQueueEntry(qe);
			continue;
		}
		if (!(ar->ArFlags & AR_first)) {
			/*
			 * Remove processed files.
			 */
			pruneArchReq(ar);
			if (ar->ArFiles == 0) {
				MessageReturnQueueEntry(qe);
				continue;
			}
			ar->ArState = ARS_schedule;
		}

		ar->ArFlags &= AR_offline | AR_segment;
		as = FindArchSet(ar->ArAsname);
		if (as == NULL) {
			Trace(TR_MISC, "Invalid ArchReq %s", arname);
			MessageReturnQueueEntry(qe);
			continue;
		}
		if (as->AsFlags & AS_disk_archive) {
			ar->ArFlags |= AR_disk;
		} else if (as->AsFlags & AS_honeycomb) {
			ar->ArFlags |= AR_honeycomb;
		}
		ar->ArDrivesUsed = 0;
		ar->ArDivides = DM_none;
		ar->ArSelFiles = ar->ArFiles;
		ar->ArSelSpace = ar->ArSpace;

		/*
		 * Process the compositions as required.
		 */
		if (ar->ArFlags & AR_offline) {
			/*
			 * Check offline files for available stage volumes.
			 */
			checkOffline(ar);
			ar->ArDivides = DM_offline;
		}
		if (ar->ArFlags & AR_segment) {
			ar->ArDivides = DM_segment;
			sortSegments(ar);
		}
		if (as->AsJoin != JM_none) {
			ar = joinFiles(ar, as);
			qe->QeAr = ar;
		}
		if (as->AsSort != SM_none) {
			sortFiles(ar, as);
		}
		if (as->AsReserve & RM_owner) {
			ar->ArDivides = (as->AsReserve & RM_dir) ?
			    DM_ownerDir : DM_ownerUidGid;
		}
		prepareArchReq(ar);
		ScheduleEnqueue(qe);
	}

	ThreadsExit();
	/*NOTREACHED*/
	return (arg);
}
//----------------------------------------------------------------------
//
//	SemInit
//
//	Initialize a semaphore to a particular value.  This just means
//	initting the process queue and setting the counter.
//
//----------------------------------------------------------------------
void
SemInit (Sem *sem, int count)
{
    QueueInit (&sem->waiting);
    sem->count = count;
}
Example #30
0
int BFS(Graph *graph, BFSVertex *start, List *hops)
{
	Queue queue;
	AdjList *adjlist = NULL;
	AdjList *adjlist_Clear = NULL;
	BFSVertex *vertex_Clear = NULL;
	BFSVertex *vertex_Adj = NULL;
	ListElmt *element = NULL;
	ListElmt *member = NULL;

	for (element = ListHead(&GraphAdjLists(graph)); element != NULL; element = ListNext(element))
	{
		vertex_Clear = ((AdjList*)ListData(element))->vertex;
		if (graph->match(vertex_Clear, start))
		{
			vertex_Clear->color = gray;
			vertex_Clear->nHops = 0;
		}
		else
		{
			vertex_Clear->color = white;
			vertex_Clear->nHops = -1;
		}
	}

	QueueInit(&queue, NULL);
	if (GraphAdjList(graph, start, &adjlist_Clear) != 0)
	{
		QueueDestroy(&queue);
		return -1;
	}
	if (QueueEnqueue(&queue, adjlist_Clear) != 0)
	{
		QueueDestroy(&queue);
		return -1;
	}

	while (QueueSize(&queue) > 0)
	{
		adjlist = QueuePeek(&queue);
		for (member = ListHead(&adjlist->Adjacent); member != NULL; member = ListNext(member))
		{
			vertex_Adj = ListData(member);

			if (GraphAdjList(graph, vertex_Adj, &adjlist_Clear))
			{
				QueueDestroy(&queue);
				return -1;
			}
			vertex_Clear = adjlist_Clear->vertex;

			if (vertex_Clear->color == white)
			{
				vertex_Clear->color = gray;
				vertex_Clear->nHops = ((BFSVertex*)adjlist->vertex)->nHops + 1;

				if (QueueEnqueue(&queue, adjlist_Clear) != 0)
				{
					QueueDestroy(&queue);
					return -1;
				}
			}
		}
		if (QueueDequeue(&queue, (void**)&adjlist) == 0)
		{
			((BFSVertex*)adjlist->vertex)->color = black;
		}
		else
		{
			QueueDestroy(&queue);
			return -1;
		}
	}
	QueueDestroy(&queue);

	ListInit(hops, NULL);
	for (element = ListHead(&GraphAdjLists(graph)); element != NULL; element = ListNext(element))
	{
		vertex_Clear = ((AdjList*)ListData(element))->vertex;
		if (vertex_Clear->nHops != -1)
		{
			if (ListInsert_Next(hops, ListTail(hops), vertex_Clear) != 0)
			{
				ListDestory(hops);
				return -1;
			}
		}
	}

	return 0;
}