Jump to content

Recommended Posts

Posted

Hi all!

Could anyone here give me a quick explanation on what's a semaphore (I guess it's like a flag?) and how to use it, with a tiny code example?

Cheers

Baptistou

Posted

Hi.

Semaphores and Mutexes are designed for controlling access to resources between tasks (threads). Semaphores and mutexes are quite similar but contain some subtle differences, I would recommend reading some FreeRTOS documentation for more on this.

For MIOS32 there is an example of using a mutex that TK has created in SVN http://svnmios.midibox.org/listing.php?repname=svn.mios32&path=%2Ftrunk%2Fapps%2Ftutorials%2F023_mutex%2F&rev=0&sc=0

The basic concept is that a task can "take" a Mutex which can relate (for example) to a device, this can then be used to restrict other tasks from accessing that device until the original task releases it.

The mutex example above restricts access to the LCD display to make sure that only one task can access the display at any one time.

I once read a good description of mutexes, if you think of it as a toilet key and only one person can have it. Once they have finished they pass the key to the next person in the queue :)

Phil

Posted

Hi,

Thanks for the explanation, that's what I expected.

I still have a question: if I understand properly the example given by TK, the tasks TASK_LCD1 and TASK_LCD2 will be stopped at line "MUTEX_LCD_TAKE" until the mutex is free.

Is there a way to skip some instructions if the mutex is not free rather than wait for it?

Baptistou

Posted (edited)

Yes absolutely, something like:


void mytask(void)

{

  while (1) {

    if (xSemaphoreTakeRecursive(xLCDSemaphore, (portTickType)1) == pdTRUE ) {

       // Do semaphore task

       xSemaphoreGiveRecursive(xLCDSemaphore); // Give semaphore back

    } else {

       // Do something else until it is free....

    }

  }

}

EDIT: pesky tab key!

Edited by philetaylor

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...