Exemplo n.º 1
0
void sem2Task  (long a0, long a1, long a2, long a3, long a4,
		long a5, long a6, long a7, long a8, long a9)
{
    WIND_TCB *pTcb = taskTcb(taskIdSelf());
    ULONG date;
    int n;

    TEST_ASSERT(pTcb != NULL);

    TEST_ASSERT(taskNameToId("Test2") == (TASK_ID)pTcb);

    TEST_MARK();

    TEST_ASSERT_OK(semTake(bsemid,WAIT_FOREVER));

    TEST_MARK();

    TEST_ASSERT_OK(semTake(bsemid,WAIT_FOREVER));

    TEST_MARK();

    TEST_ASSERT_OK(taskResume(a0));

    TEST_MARK();
    date = tickGet();
    for (n = 0; n < 1000000; n++) {
	    ULONG old_date = date;
	    date = tickGet();
	    if (date != old_date)
		    TEST_MARK();
    }

    TEST_MARK(); /* Should not pass this mark */
}
Exemplo n.º 2
0
void pe_dispatcher()
{
	int i;
	Message msg;
	
	for(;;)
	{
		msgQReceive(msgQ_dispatcher, (char*)&msg, sizeof(msg), WAIT_FOREVER);
		
		semTake(mut_table_capt, WAIT_FOREVER);
		// On cherche si
		for(i=0; i < DEVICE_MAX_COUNT; ++i)
		{
			if(table_capt[i].specific.state == opened &&
			   table_capt[i].specific.address == msg.date.tv_nsec)
			// On fait passer l'adresse par la date non initialisé pour éviter des champs de mémoire supplémentaire inutile.
			{
				// Trouvé : on ne drop pas le message.
				clock_gettime(CLOCK_REALTIME, &(msg.date));

				semTake(mut_table_buffer, WAIT_FOREVER);
				memcpy((char*)&(table_buffer[i]), (char*)&msg, sizeof(Message));
				semGive(mut_table_buffer);
				
				break;
			}
		}
		semGive(mut_table_capt);
	}
}
Exemplo n.º 3
0
void Philosopher (int i, int Philos)   {
	while (1) {

             if (i==Philos-1){
 				taskDelay (DELAY_TICKS);
 				printf("Philosopher %d - start thinking\n", i+1);
 				semTake(Sema_fork[0], WAIT_FOREVER);
 				taskDelay(X);
 				semTake (Sema_fork[Philos-1], WAIT_FOREVER);
 				printf("Philosopher %d - start eating\n", i+1);
 				taskDelay(10);
 				semGive(Sema_fork[Philos-1]);
 				semGive(Sema_fork[0]);
                p[i]++;
            	           	 
             }
             else {
				taskDelay (DELAY_TICKS);
				printf("Philosopher %d - start thinking\n", i+1);
				semTake(Sema_fork[i], WAIT_FOREVER);
				taskDelay(X);
				semTake (Sema_fork[i+1], WAIT_FOREVER);
				printf("Philosopher %d - start eating\n", i+1);
				taskDelay(10);
				semGive(Sema_fork[i]);
				semGive(Sema_fork[i+1]);
                p[i]++;
              }		
	};
	
}
Exemplo n.º 4
0
/**
 * @brief Enlever un périphérique.
 * @param i L'index du device à enlever
 * @return OK pour un succès, ERROR sinon. 
 */
int pe_deviceRemove(int i)
{
	semTake(mut_table_capt, WAIT_FOREVER);
	if(i < DEVICE_MAX_COUNT && table_capt[i].specific.state != notcreated)
	{	
		iosDevDelete((DEV_HDR*)&(table_capt[i]));
		table_capt[i].specific.state = notcreated;
		table_capt[i].specific.address = -1;
		semGive(mut_table_capt);
		
		semTake(mut_table_capt, WAIT_FOREVER);
		table_buffer[i].id = -1;
		semGive(mut_table_buffer);
		
		return OK;
	}
	else
	{
		// Le capteur n'a pas été crée :
		// " If the device was never added to the device list, 
		//   unpredictable results may occur."
		semGive(mut_table_capt);
		errnoSet(ENEXIST);
		return ERROR;
	}
}
Exemplo n.º 5
0
/*!*****************************************************************************
*******************************************************************************
\note  send_sim_state
\date  Nov. 2007
   
\remarks 

sends the entire joint_sim_state to shared memory
	

*******************************************************************************
Function Parameters: [in]=input,[out]=output

none

******************************************************************************/
int 
send_sim_state(void)
{
  
  int i;

  // joint state
  if (semTake(sm_joint_sim_state_sem,ns2ticks(TIME_OUT_NS)) == ERROR) {
    
    ++simulation_servo_errors;
    return FALSE;

  } 

  cSL_Jstate(joint_sim_state,sm_joint_sim_state_data,n_dofs,DOUBLE2FLOAT);
    
  for (i=1; i<=n_dofs; ++i)
    sm_joint_sim_state->joint_sim_state[i] = sm_joint_sim_state_data[i];

  sm_joint_sim_state->ts = simulation_servo_time;
  
  semGive(sm_joint_sim_state_sem);


  // base state
  if (semTake(sm_base_state_sem,ns2ticks(TIME_OUT_NS)) == ERROR) {
    
    ++simulation_servo_errors;
    return FALSE;

  } 

  cSL_Cstate((&base_state)-1, sm_base_state_data, 1, DOUBLE2FLOAT);

  sm_base_state->state[1] = sm_base_state_data[1];

  sm_base_state->ts = simulation_servo_time;
  
  semGive(sm_base_state_sem);


  // base orient
  if (semTake(sm_base_orient_sem,ns2ticks(TIME_OUT_NS)) == ERROR) {
    
    ++simulation_servo_errors;
    return FALSE;

  } 

  cSL_quat(&base_orient-1, sm_base_orient_data, 1, DOUBLE2FLOAT);

  sm_base_orient->orient[1] = sm_base_orient_data[1];

  sm_base_orient->ts = simulation_servo_time;
  
  semGive(sm_base_orient_sem);


  return TRUE;
}
Exemplo n.º 6
0
os_result os_mutexInit (os_mutex *mutex, const os_mutexAttr *mutexAttr)
{
    os_mutexAttr defAttr;
    os_result rv;
    int options;
    SEM_ID id;

    assert (mutex != NULL);
    #ifdef OSPL_STRICT_MEM
    assert (mutex->signature != OS_MUTEX_MAGIC_SIG);
#endif

    if(!mutexAttr) {
        os_mutexAttrInit(&defAttr);
        mutexAttr = &defAttr;
    }

    options = (SEM_Q_PRIORITY | SEM_DELETE_SAFE);
    /* Set option for priority inheritance if feature is enabled */
    if (ospl_mtx_prio_inherit) {
        options = options | SEM_INVERSION_SAFE;
    }
    if (mutexAttr->scopeAttr == OS_SCOPE_SHARED) {
        /* create named mutex using shared address as unique name */
        snprintf (mutex->name, sizeof (mutex->name), "/%lu", (os_uint32) mutex);
        id = semOpen (mutex->name, SEM_TYPE_MUTEX, SEM_EMPTY, options, OM_CREATE|OM_EXCL, NULL);
        /* As it may exist from a previous run. remove leftover semaphore object */
        if (id != NULL) {
            /* a fresh one, initialise it and cache the SEM_ID */
            pa_st32 ((void *) &mutex->info.id, 0);
            semTake (cache_lock, WAIT_FOREVER);
            (void) ut_tableInsert ((ut_table) cache, mutex, id);
            semGive (cache_lock);
        } else {
            /* re-using an old one: it should have been destroyed and hence should have a marker in info.id */
            id = get_mutex (mutex);
            if (id != NULL) {
                semTake (id, WAIT_FOREVER);
                semGive (id);
                /*cas_mutex_info_id ((void*)&mutex->info.id, invalid_sem_id, 0);*/
            } else {
                mutex_panic ("init: attempt to reuse semaphore currently in use", 0);
            }
        }

        rv = (id != NULL) ? os_resultSuccess : os_resultFail;
    } else {
        int result;
        mutex->name[0] = '\0';
        /* TODO attrs */
        result = pthread_mutex_init(&mutex->info.posix_mutex, NULL);
        rv = (result == 0) ? os_resultSuccess : os_resultFail;
    }

#ifdef OSPL_STRICT_MEM
    mutex->signature = OS_MUTEX_MAGIC_SIG;
#endif
    return rv;
}
Exemplo n.º 7
0
Preferences::~Preferences()
{
    semTake(m_tableLock, WAIT_FOREVER);
    semDelete(m_tableLock);
    semTake(m_fileLock, WAIT_FOREVER);
    semDelete(m_fileOpStarted);
    semDelete(m_fileLock);
}
Exemplo n.º 8
0
int RandomizerThreadFunc(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8, int p9, int p10)
{
    int operation, semIdx, semTimeout;
    int stat=0;

    while(1)
    {	
        operation  = (int) (rand() * 2.) / RAND_MAX;
        semIdx	   = (int) (rand() * 2.) / RAND_MAX;
        semTimeout = (int) rand() * 5. / RAND_MAX;

        switch( operation )
        {
            case 0:	
                cTake++;
                switch( semIdx )
                {
                    case 0: stat = semTake( s_binary, semTimeout );break;
                    case 1: stat = semTake( s_counting, semTimeout );break;
                }
                if ( OK != stat )
                {
                    if( S_objLib_OBJ_TIMEOUT == errno || S_objLib_OBJ_UNAVAILABLE == errno )
                    {
                        cTakeTimeout++;
                    }
                    else
                    {
                        cTakeErr++;
                        puts("");
                        perror("Error taking semaphore");
                    }
                }
                break;

            case 1:
                cGive++;
                switch( semIdx )
                {
                    case 0: stat = semGive( s_binary );break;
                    case 1: stat = semGive( s_counting );break;
                }
                if ( OK != stat )
                    cGiveErr++;
                break;
            default:break;

        } //switch( operation )

    } //while(1)
}
Exemplo n.º 9
0
static DMA_MSG *getDmaBuffer (SND_DEV *pDev)
{
  DMA_MSG *dmaBuffer;

  semTake (pDev->bufSem, WAIT_FOREVER);

  semTake (pDev->devSem, WAIT_FOREVER);
/*  dmaBuffer = snd_dmaBuffer + pDev->dmaIndex * MAX_DMA_SIZE;*/
  dmaBuffer = &snd_buffer[pDev->dmaIndex];
  pDev->dmaIndex = (pDev->dmaIndex + 1) % MAX_DMA_MSGS;
  semGive (pDev->devSem);

  return dmaBuffer;
}
Exemplo n.º 10
0
void RWProtect::startRead() {
    // Lock m_numReaders mutex
    semTake( m_numReadMutex , WAIT_FOREVER );

    // Add reader to room
    m_numReaders++;

    // If this is the first reader, wait for the room to be empty
    if ( m_numReaders == 1 ) {
        semTake( m_roomEmpty , WAIT_FOREVER );
    }

    // Unlock m_numReaders mutex
    semGive( m_numReadMutex );
}
Exemplo n.º 11
0
int devDelete(char* devName)
{
	myDev * i = first;
	char * pNameTail;
	myDev * dev = (myDev*) iosDevFind (devName,&pNameTail);
	if ((*pNameTail)!='\0' || dev==NULL)
	//If pNameTail is not '\0', either we don't have an exact match
	//or we have no match at all
	{
		errnoSet(UNKNOWN_DEVICE);
		semGive(semMAdmin);
		return -1;
	}
	if(semMAdmin==0)
	{
		errnoSet(NOT_INSTALLED);
		return -1;
	}
	if(semTake(semMAdmin,WAIT_FOREVER)==-1)
	{
		errnoSet(SEM_ERR);
		return -1;
	}
	
	if (dev->openned != 0)
	{
		//There are still openned file descriptors on this device,
		//we can't delete it, give back semaphores and leave.
		semGive(dev->semMData);
		errnoSet(OPENNED_DEV);
		semGive(semMAdmin);
		return -1;
	}
	iosDevDelete((DEV_HDR*)dev); //This only prevents further oppenings. 
	//Find and delete the device in device list :
	if (dev==first)
	{
		first=dev->next;
	} else {
		for (i=first;i->next!=dev;i=i->next);
		i->next=dev->next;
	}
	semTake(dev->semMData,WAIT_FOREVER); //Let pending ops on this dev finish
	semDelete(dev->semMData); //We don't need to release it to delete it
	free(dev);
	semGive(semMAdmin);
	return 0;
}
Exemplo n.º 12
0
//------------------------------------------------------------------------------
// Function:    ShbIpcThreadSignalJobReady
//
// Description: Thread for new data Job Ready signaling
//
// Parameters:
//      pvThreadParam_p         user parameters for thread
//
// Return:      void *          thread exit value (not used)
//------------------------------------------------------------------------------
int ShbIpcThreadSignalJobReady (int pvThreadParam_p)
{
    tShbInstance        pShbInstance;
    tShbMemInst         *pShbMemInst;
    tShbMemHeader*      pShbMemHeader;
    INT                 iRetVal;
    UINT                fTimeOut;

    EPL_DBGLVL_SHB_TRACE("%s(): ThreadId:%ld\n", __func__);

    pShbInstance = (tShbMemInst*)pvThreadParam_p;
    pShbMemInst = ShbIpcGetShbMemInst (pShbInstance);
    pShbMemHeader = ShbIpcGetShbMemHeader (pShbInstance);

    pShbMemInst->m_fJobReadyThreadStarted = TRUE;

    if (pShbMemInst->m_ulTimeOutMsJobReady != 0)
    {
    	// todo: timeout is in ticks!!
        iRetVal = semTake(pShbMemHeader->m_semJobReady,
        		          pShbMemInst->m_ulTimeOutMsJobReady);
    }
    else
    {
        iRetVal = semTake(pShbMemHeader->m_semJobReady, WAIT_FOREVER);
    }

    if (iRetVal == OK)
    {
        fTimeOut = FALSE;
    }
    else
    {
        /* timeout or error */
        fTimeOut = TRUE;
    }

    if (pShbMemInst->m_pfnSigHndlrJobReady != NULL)
    {
        //call Handler
        pShbMemInst->m_pfnSigHndlrJobReady(pShbInstance, fTimeOut);
    }

    pShbMemInst->m_pfnSigHndlrJobReady = NULL;
    pShbMemInst->m_fJobReadyThreadStarted = FALSE;

    return 0;
}
Exemplo n.º 13
0
NetworkTable::~NetworkTable()
{
	delete m_hasAdded;
	delete m_hasChanged;
	delete m_transaction;
	semTake(m_listenerLock, WAIT_FOREVER);
	m_connectionListeners.clear();
	m_additionListeners.clear();
	m_listeners.clear();
	m_listenToAllListeners.clear();
	semDelete(m_listenerLock);
	semTake(m_dataLock, WAIT_FOREVER);
	m_connections.clear();
	m_data.clear();
	semDelete(m_dataLock);
}
Exemplo n.º 14
0
//------------------------------------------------------------------------------
// Function:    ShbIpcEnterAtomicSection
//
// Description: Enter atomic section for Shared Buffer access
//
// Parameters:  pShbInstance_p          pointer to shared buffer instance
//
// Return:      tShbError      = error code
//------------------------------------------------------------------------------
tShbError  ShbIpcEnterAtomicSection (tShbInstance pShbInstance_p)
{
    tShbMemInst         *pShbMemInst;
    tShbMemHeader       *pShbMemHeader;
    tShbError           ShbError;

    if (pShbInstance_p == NULL)
    {
        return (kShbInvalidArg);
    }

    pShbMemInst = ShbIpcGetShbMemInst (pShbInstance_p);
    pShbMemHeader = ShbIpcGetShbMemHeader (pShbMemInst);

    if (semTake (pShbMemHeader->m_mutexBuffAccess, TIMEOUT_ENTER_ATOMIC) == OK)
    {
        ShbError = kShbOk;
    }
    else
    {
        ShbError = kShbBufferInvalid;
    }

    return (ShbError);
}
Exemplo n.º 15
0
//------------------------------------------------------------------------------
// Function:    ShbIpcThreadSignalNewData
//
// Description: Thread for new data signaling
//
// Parameters:
//      pvThreadParam_p         user parameters for thread
//
// Return:      void *          thread exit value (not used)
//------------------------------------------------------------------------------
int ShbIpcThreadSignalNewData (int pvThreadParam_p)
{
    tShbInstance        pShbInstance;
    tShbMemInst*        pShbMemInst;
    tShbMemHeader*      pShbMemHeader;
    INT                 iRetVal;

    /* thread parameter contains pointer to shared memory */
    pShbInstance = (tShbMemInst*)pvThreadParam_p;

    pShbMemInst = ShbIpcGetShbMemInst (pShbInstance);
    pShbMemHeader = ShbIpcGetShbMemHeader (pShbInstance);

    /* signal that thread is running */
    pShbMemInst->m_fNewDataThreadStarted = TRUE;

    do
    {
        if ((iRetVal = semTake(pShbMemHeader->m_semNewData,
        		               TIMEOUT_CANCEL_THREAD)) == OK)
        {
            //check terminate flag
            if (!pShbMemInst->m_fThreadTermFlag)
            {
                pShbMemInst->m_pfnSigHndlrNewData(pShbInstance);
            }
        }
    } while(!pShbMemInst->m_fThreadTermFlag);

    //set sem thread terminated
    pShbMemInst->m_fNewDataThreadStarted = FALSE;
    semGive(pShbMemHeader->m_semStopSignalingNewData);

    return 0;
}
Exemplo n.º 16
0
/**
 * Execute a transaction with a Jaguar that sets some property.
 *
 * Jaguar always acks when it receives a message.  If we don't wait for an ack,
 * the message object in the Jaguar could get overwritten before it is handled.
 *
 * @param messageID The messageID to be used on the CAN bus (device number is added internally)
 * @param data The up to 8 bytes of data to be sent with the message
 * @param dataSize Specify how much of the data in "data" to send
 */
void CANJaguar::setTransaction(uint32_t messageID, const uint8_t *data, uint8_t dataSize)
{
    uint32_t ackMessageID = LM_API_ACK | m_deviceNumber;
    int32_t localStatus = 0;

    // If there was an error on this object and it wasn't a timeout, refuse to talk to the device
    // Call ClearError() on the object to try again
    if (StatusIsFatal() && GetError().GetCode() != -44087)
	return;

    // Make sure we don't have more than one transaction with the same Jaguar outstanding.
    semTake(m_transactionSemaphore, WAIT_FOREVER);

    // Throw away any stale acks.
    receiveMessage(&ackMessageID, NULL, 0, 0.0f);
    // Send the message with the data.
    localStatus = sendMessage(messageID | m_deviceNumber, data, dataSize);
    wpi_setErrorWithContext(localStatus, "sendMessage");
    // Wait for an ack.
    localStatus = receiveMessage(&ackMessageID, NULL, 0);
    wpi_setErrorWithContext(localStatus, "receiveMessage");

    // Transaction complete.
    semGive(m_transactionSemaphore);
}
Exemplo n.º 17
0
/**
 * Execute a transaction with a Jaguar that gets some property.
 *
 * Jaguar always generates a message with the same message ID when replying.
 *
 * @param messageID The messageID to read from the CAN bus (device number is added internally)
 * @param data The up to 8 bytes of data that was received with the message
 * @param dataSize Indicates how much data was received
 */
void CANJaguar::getTransaction(uint32_t messageID, uint8_t *data, uint8_t *dataSize)
{
    uint32_t targetedMessageID = messageID | m_deviceNumber;
    int32_t localStatus = 0;

    // If there was an error on this object and it wasn't a timeout, refuse to talk to the device
    // Call ClearError() on the object to try again
    if (StatusIsFatal() && GetError().GetCode() != -44087)
    {
	if (dataSize != NULL)
	    *dataSize = 0;
	return;
    }

    // Make sure we don't have more than one transaction with the same Jaguar outstanding.
    semTake(m_transactionSemaphore, WAIT_FOREVER);

    // Throw away any stale responses.
    receiveMessage(&targetedMessageID, NULL, 0, 0.0f);
    // Send the message requesting data.
    localStatus = sendMessage(targetedMessageID, NULL, 0);
    wpi_setErrorWithContext(localStatus, "sendMessage");
    // Caller may have set bit31 for remote frame transmission so clear invalid bits[31-29]
    targetedMessageID &= 0x1FFFFFFF;
    // Wait for the data.
    localStatus = receiveMessage(&targetedMessageID, data, dataSize);
    wpi_setErrorWithContext(localStatus, "receiveMessage");

    // Transaction complete.
    semGive(m_transactionSemaphore);
}
Exemplo n.º 18
0
void StateMachine :: runToCompletion() {
	std::string actualEvent;
	int d,i,j;
	while (TRUE) {
		semTake (semEvent, WAIT_FOREVER);
		actualEvent = getEvent(); // Get the event from the queue
		//printf(actualEvent.c_str()); // For debug purposes only
		for (d = 0; d < diagrams; d++) {
			for (i = 0; i < lines[d]; i++) {
				if ((actualState[d] == tab[d][i]->actState) && 
						(actualEvent == tab[d][i]->myEvent) && 
						((*tab[d][i]->condition)() == TRUE)) { // Call the condition function which returns bool
					actualState[d] = tab[d][i]->nextState;
					(*tab[d][i]->action)(); //Call the funtion defined by pointer action
					for (j = 0; j < lines[d]; j++) {
						if ((actualState[d] == tab[d][j]->actState) && 
								(tab[d][j]->myEvent == (diaTimerTable[d]->timerName))) {
							diaTimerTable[d]->startTimer(tab[d][j]->eventTime); // Look for timers to start next
							break;
						}
					}
					break;
				}
			}
		}
	}
}
static tEplKernel EplApiProcessImageWaitForCompletion(
    tEplApiProcessImageCopyJobInt* pCopyJob_p)
{
    tEplKernel      Ret = kEplSuccessful;

#if (TARGET_SYSTEM == _LINUX_) && defined(__KERNEL__)
    int             iRes;

    iRes = wait_for_completion_interruptible(&pCopyJob_p->m_Event.m_pCompletion->m_Completion);
    if (iRes != 0)
    {
        Ret = kEplShutdown;
    }

#elif (TARGET_SYSTEM == _LINUX_) && !defined(__KERNEL__)
    sem_wait(&pCopyJob_p->m_Event.m_semCompletion);
#elif (TARGET_SYSTEM == _WIN32_)
    WaitForSingleObject(pCopyJob_p->m_Event.m_hEvent, INFINITE);
#elif (TARGET_SYSTEM == _VXWORKS_)
    semTake(pCopyJob_p->m_Event.m_semCompletion, WAIT_FOREVER);
#else
#error "OS currently not supported by EplApiProcessImage!"
#endif

//Exit:
    return Ret;
}
Exemplo n.º 20
0
/**
 * Free the resources for a timer event.
 * All resources will be freed and the timer event will be removed from the
 * queue if necessary.
 */
Notifier::~Notifier()
{
    tRioStatusCode localStatus = NiFpga_Status_Success;
    {
        Synchronized sync(queueSemaphore);
        DeleteFromQueue();

        // Delete the static variables when the last one is going away
        if (!(--refcount))
        {
            talarm->writeEnable(false, &localStatus);
            delete talarm;
            talarm = NULL;
            manager->disable(&localStatus);
            delete manager;
            manager = NULL;
        }
    }
    wpi_setError(localStatus);

    // Acquire the semaphore; this makes certain that the handler is 
    // not being executed by the interrupt manager.
    semTake(m_handlerSemaphore, WAIT_FOREVER);
    // Delete while holding the semaphore so there can be no race.
    semDelete(m_handlerSemaphore);
}
Exemplo n.º 21
0
/*
    Lock a mutex
 */
PUBLIC void mprSpinLock(MprSpin *lock)
{
    if (lock == 0) return;

#if ME_DEBUG
    /*
        Spin locks don't support recursive locking on all operating systems.
     */
    assert(lock->owner != mprGetCurrentOsThread());
#endif

#if USE_MPR_LOCK
    mprTryLock(&lock->cs);
#elif MACOSX
    OSSpinLockLock(&lock->cs);
#elif ME_UNIX_LIKE && ME_COMPILER_HAS_SPINLOCK
    pthread_spin_lock(&lock->cs);
#elif ME_UNIX_LIKE
    pthread_mutex_lock(&lock->cs);
#elif ME_WIN_LIKE
    if (!lock->freed) {
        EnterCriticalSection(&lock->cs);
    }
#elif VXWORKS
    semTake(lock->cs, WAIT_FOREVER);
#endif
#if ME_DEBUG
    assert(lock->owner != mprGetCurrentOsThread());
    lock->owner = mprGetCurrentOsThread();
#endif
}
int RecvTask(   int sockfd/* server's socket fd */  )
{
	/*int i,j;*/
        while(1) 
        {
            /*nRead = read(newFd, adNauseam, sizeof (adNauseam));
            if ( nRead < 0 )
            {
                perror ("read");
                close (sFd);
                return (ERROR);
	    }*/
        static int kk=0;
        kk++;
            semTake(SEM_DMA_Playback, WAIT_FOREVER);
           /* semTake(SEM_Sample, WAIT_FOREVER);*/
            loadbuffer(saved_samples, DAC_BUFFER_SIZE);
	    	if(DTC_DMA_Playback)
	    	{
	    		printf("\e[1;1H task0=%d     %d \n", kk);
                memmove(DAC_BUFFER+(DAC_BUFFER_SIZE/2),saved_samples/*adNauseam*/, (DAC_BUFFER_SIZE/2));
	    	}
            else
            {
            	printf("\e[1;40H task1=%d    [%d]  \n", kk );
                memmove(DAC_BUFFER,/*adNauseam*/saved_samples, (DAC_BUFFER_SIZE/2));
            }
	   

        } /* end while awaiting frames */
// Lab01/2 -  for third task
void tWrite(void){
	while(1){
		beLazy(100);
		char stringBufferPot[50];
		char stringBufferTemp[50];
		char stringBufferKey[50];
		
		semTake(writeSem, WAIT_FOREVER);
		sprintf(stringBufferTemp, "Temperature: %d   ",AInTemp);
		//sprintf(stringBufferPot, "Potentiomenter: %d   ",AInPot);
		sprintf(stringBufferKey, "Gedrueckte Taste: %d   ", key);
		
		if(key == 49){
			sprintf(stringBufferPot, "Potentiometer: %d                      ",AInPot);
		}
		else if(key == 50){
			//calculation of the voltage based on the input value 58...4095
			float k = (5.0/4037);
			float d = (float)(-k*58);
			float calc = (float)(k* AInPot+d);
			sprintf(stringBufferPot, "Potentiometer: %f V                      ",calc);
		}
		else if (key == 51){
			sprintf(stringBufferPot, "Potentiometer: %x                        ", AInPot);
		}
		else{
			sprintf(stringBufferPot, "Error - key 1,2 or 3 should be used");
		}
		writeToDisplay(0,0, stringBufferPot);
		writeToDisplay(1,0, stringBufferTemp);
		writeToDisplay(2,0, stringBufferKey);
		semGive(writeSem);
	}
}
Exemplo n.º 24
0
Arquivo: udp.c Projeto: unitedmne/sim
void UDP_Send(sint32 fd)
{
    sint32 rst;
    sint32 rsem;
    UDP_Load();
    UDP_PackSendData();
    rst = UDP_WriteData(fd);
    
    if (rst < 0)
    {
        DBG_ERRO_0("[UDP] udp send error!");
    }
    
    // return OK, or ERROR if the semaphore ID is invalid or the task timed out.
    rsem = semTake(udpRecvTmsSemID, NO_WAIT);
    
    // if have new tms data
    if (rsem == OK)
    {
        UDP_Load_Tms();
        UDP_PackSendTmsData();
		
        // todo only for test
        //show_udp_send_tms_data();
		
        rst = UDP_WriteTmsData(fd);
        
        if (rst < 0)
        {
            DBG_ERRO_0("[UDP] udp send tms error!");
        }
    }
}
Exemplo n.º 25
0
void CSVReader::ReloadValues()
{
	semTake(m_lock,WAIT_FOREVER);
	m_map.clear();
	FillMap();
	semGive(m_lock);
}
Exemplo n.º 26
0
STATUS virtualStackDelete
    (
    VSID vsid 				/* VID returned by virtualStackCreate */
    )
    {
    int vsIndex;
    
    semTake (vsTblLock, WAIT_FOREVER);
    
    for (vsIndex = 0; vsIndex < VSID_MAX; vsIndex++)
        if (vsTbl[vsIndex] == vsid)
            break; /* Hey, we found it! */

    /* Check that we did find it. */
    if (vsIndex == VSID_MAX)
        {
        semGive (vsTblLock);
        return (ERROR);
        }

    /* Free the structure. */
    KHEAP_FREE (vsTbl[vsIndex]);

    /* Let's be extra paranoid. */
    vsTbl[vsIndex] = NULL;
    
    semGive (vsTblLock);

    return (OK);

    }
Exemplo n.º 27
0
int OtherThreadFunc(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8, int p9, int p10)
{
    Wait4State( BINARY_OTHER );

    Go2State( BINARY_OPPOSITE, "BINARY_OPPOSITE" );
    if( semGive( s_binary ) != OK )
        perror( "Error giving in BINARY_OTHER state" );

    Wait4State( COUNTING_OTHER );

    Go2State( COUNTING_OPPOSITE, "COUNTING_OPPOSITE" );
    if( semGive( s_counting ) != OK )
        perror( "Error giving in COUNTING_OTHER state" );

    Wait4State( MUTEX_OTHER_GIVE );
    if( semGive( s_mutex ) == OK )
        printf( "Error in MUTEX_OTHER_GIVE: give operation must fail, but it succeeded\n");

    Go2State( MUTEX_OTHER_WAIT, "MUTEX_OTHER_WAIT" );
    if( semTake( s_mutex, WAIT_FOREVER ) != OK )
        perror( "Error taking in MUTEX_OTHER_WAIT state" );

    CheckState(MUTEX_OTHER_WAIT, MUTEX_GIVE_ALL );

    Go2State( MUTEX_OPPOSITE_TO, "MUTEX_OPPOSITE_TO" );

    Wait4State( MUTEX_OPPOSITE_GIVE );
    if( semGive( s_mutex ) != OK )
        perror("Error giving in MUTEX_OPPOSITE_GIVE state");

    Wait4State( MUTEX_UNBLOCK );
    printf( "Other thread is complete.\n");

    return 0;
}
Exemplo n.º 28
0
STATUS virtualStackIdGet
    (
    char* pName, 			/* Name that was used in virtualStackCreate */
    VSID* pVSID
    )
    {
    int vsIndex;

    semTake (vsTblLock, WAIT_FOREVER);
    
    for (vsIndex = 0; vsIndex < VSID_MAX; vsIndex++)
        if (!strncmp (vsTbl[vsIndex]->pName, pName, 
		      min (strlen (pName), VS_NAME_MAX)))
            break; /* Hey, we found it! */

    /* Check that we did find it. */
    if (vsIndex == VSID_MAX)
        {
        semGive(vsTblLock);
        return (ERROR);
        }

    *pVSID = vsTbl[vsIndex];

    semGive (vsTblLock);

    return (OK);
    }
Exemplo n.º 29
0
/* Function: ExtSetHostPkt =====================================================
 * Abstract:
 *  Sets (sends) the specified number of bytes on the comm line.  As long as
 *  an error does not occur, this function is guaranteed to set the requested
 *  number of bytes.  The number of bytes set is returned via the 'nBytesSet'
 *  parameter.  EXT_NO_ERROR is returned on success, EXT_ERROR is returned on
 *  failure.
 *
 * NOTES:
 *  o it is always o.k. for this function to block if no room is available
 */
PUBLIC boolean_T ExtSetHostPkt(
    const ExtUserData *UD,
    const int         nBytesToSet,
    const char        *src,
    int               *nBytesSet)
{
    boolean_T errorCode = EXT_NO_ERROR;
	int_T rtIOStreamErrorStatus;
	*nBytesSet = 0;	/* assume */

    #ifdef VXWORKS
        semTake(commSem, WAIT_FOREVER);
    #endif

    /* Blocks until all requested outgoing data is sent */
    rtIOStreamErrorStatus = rtIOStreamBlockingSend(UD->streamID,
                                                   (const void * const) src,
                                                   (uint32_T) nBytesToSet);
    
    if (rtIOStreamErrorStatus == RTIOSTREAM_ERROR) {
        errorCode = EXT_ERROR;
    } else { 
        *nBytesSet = nBytesToSet;
    }
    
    #ifdef VXWORKS
        semGive(commSem);
    #endif

    return errorCode;

} /* end ExtSetHostPkt */
Exemplo n.º 30
0
void virtualStackInfo
    (
    VSID vsid
    )
    {
    int vsIndex;
    
    if (vsid == NULL)
        return;

    semTake (vsTblLock, WAIT_FOREVER);
    
    for (vsIndex = 0; vsIndex < VSID_MAX; vsIndex++)
        if (vsTbl[vsIndex] == vsid)
            break; /* Hey, we found it! */

    /* Check that we did find it. */
    if (vsIndex == VSID_MAX)
        {
        semGive(vsTblLock);
        return;
        }

    printf ("Index: %d \tName: %s\n", vsIndex,
           vsTbl[vsIndex]->pName);

    semGive(vsTblLock);

    }