5 years, 3 months ago.

What is the expected behaviour with Semaphores?

I'm getting a bit confused by the behaviour of Semaphores. Could I get some clarifications on the expected behaviour? I'm replacing the mutex in the UARTSerial driver to prevent errors getting thrown due to mutex failures when 2 threads access printf.

So what I'm expecting is that the Semaphore holds a thread until it can acquire the resource.

Semaphore.cpp

/** Wait until a Semaphore resource becomes available.
      @note You cannot call this function from ISR context.
    */
void Semaphore::acquire()
{
    osStatus_t status = osSemaphoreAcquire(_id, osWaitForever);
    if (status != osOK) {
        MBED_ERROR1(MBED_MAKE_ERROR(MBED_MODULE_KERNEL, MBED_ERROR_CODE_SEMAPHORE_LOCK_FAILED), "Semaphore acquire failed", status);
    }
}

However osSemaphoreAcquire seems to not do this behaviour, in fact it returns a timeout error even if the timeout period was 'osWaitForever'. So Semaphore::acquire() will actually throw an exception.

rtx_semaphore.c

/// Acquire a Semaphore token or timeout if no tokens are available.
osStatus_t osSemaphoreAcquire (osSemaphoreId_t semaphore_id, uint32_t timeout) {

The now deprecated wait function returns a value I can use in my case with a while loop. But more importantly to me, doesn't throw an error.

Semaphore.cpp (Combined with _wait() function)

/** Wait until a Semaphore resource becomes available.
    */
int32_t Semaphore::wait(uint32_t millisec = osWaitForever)
{
    osStatus_t stat = osSemaphoreAcquire(_id, millisec);
    switch (stat) {
        case osOK:
            return osSemaphoreGetCount(_id) + 1;
        case osErrorTimeout:
        case osErrorResource:
            return 0;
        case osErrorParameter:
        default:
            return -1;
}

My current work around is this:

UARTSerial.cpp

rtos::Semaphore _sema_lock; // This is a private member in the UARTSerial Class
void UARTSerial::api_lock(void)
{
	while(_sema_lock.wait() <= 0) {
		wait_ms(1);
	}
}

So what is the actual expected behaviour?

2 Answers

5 years, 3 months ago.

Try binary instead of mutex and check how it responds. Can you please share the exact output of this coding? The logical errors can be solved by analyzing the output. Or, you can get experts' assistance from Essays Chief to solve the issue.

5 years, 2 months ago.

Whether you need to get a high grade in your creative writing class or want to make the best impression to a college admissions committee or professional, your best bet is to order our custom writing services. https://topwritingservice.com/letter-writing-service/ It will save your time