modm API documentation
modm::pt::Semaphore Class Reference

Counting semaphore. More...

#include <modm/processing/protothread/semaphore.hpp>

Public Member Functions

 Semaphore (uint16_t initial)
 Create a counting semaphore. More...
 
bool acquire ()
 Acquire the semaphore. More...
 
void release ()
 Release the semaphore. More...
 

Protected Attributes

uint16_t count
 

Detailed Description

Counting semaphore.

This module implements counting semaphores on top of protothreads. Semaphores are a synchronization primitive that provide two operations: acquire() and release(). Sometimes these operations are also called wait and signal. The acquire() operation checks the semaphore counter and "blocks" the thread if the counter is zero. The release() operation increases the semaphore counter but does not block. If another thread has blocked waiting for the semaphore that is signalled, the blocked thread will become runnable again.

This class can for example be used for resource limiting or credit tracking:

Resource limit:

  • initial = number of resources
  • acquire() to gain access to a resource
  • release() to release the resource

Credit tracking:

As protothreads implement a form cooperative multithreading no synchronisation is needed for accessing global variables or for critical sections. Just don't use PT_YIELD() or PT_WAIT_UNTIL() inside a critical sections and you're fine.

Therefore there's no Mutex implementation, it isn't needed.

Constructor & Destructor Documentation

modm::pt::Semaphore::Semaphore ( uint16_t  initial)
inline

Create a counting semaphore.

Parameters
initialInitial value

Member Function Documentation

bool modm::pt::Semaphore::acquire ( )
inline

Acquire the semaphore.

The "acquire" or "wait" operation causes the protothread to block while the counter is zero. When the counter reaches a value larger than zero, the protothread will continue.

Use this always within a PT_WAIT_UNITL() macro inside a modm::pt::Thread::run() method.

PT_WAIT_UNTIL(semaphore.acquire());
Returns
false if the Semaphore count not be acquired, true if the operation was successful.
void modm::pt::Semaphore::release ( )
inline

Release the semaphore.

The "release" or "signal" operation increments the counter inside the semaphore, which eventually will cause waiting protothreads to continue executing.


The documentation for this class was generated from the following file: