Mistake on this page?
Report an issue in GitHub or email us

Semaphore

Semaphore class hierarchy

A semaphore manages thread access to a pool of shared resources of a certain type.

Semaphore class reference

Public Member Functions
 Semaphore (int32_t count=0)
 Create and Initialize a Semaphore object used for managing resources. More...
 Semaphore (int32_t count, uint16_t max_count)
 Create and Initialize a Semaphore object used for managing resources. More...
int32_t wait (uint32_t millisec=osWaitForever)
 Wait until a Semaphore resource becomes available. More...
int32_t wait_until (uint64_t millisec)
 Wait until a Semaphore resource becomes available. More...
void acquire ()
 Wait until a Semaphore resource becomes available. More...
bool try_acquire ()
 Try to acquire a Semaphore resource, and return immediately. More...
bool try_acquire_for (uint32_t millisec)
 Wait until a Semaphore resource becomes available. More...
bool try_acquire_until (uint64_t millisec)
 Wait until a Semaphore resource becomes available. More...
osStatus release (void)
 Release a Semaphore resource that was obtain with Semaphore::acquire. More...
 ~Semaphore ()
 Semaphore destructor. More...

Semaphore example

Use Semaphore to protect printf().

#include "mbed.h"

Semaphore one_slot(1);
Thread t2;
Thread t3;

void test_thread(void const *name) {
    while (true) {
        one_slot.wait();
        printf("%s\n\r", (const char*)name);
        wait(1);
        one_slot.release();
    }
}

int main (void) {
    t2.start(callback(test_thread, (void *)"Th 2"));
    t3.start(callback(test_thread, (void *)"Th 3"));

    test_thread((void *)"Th 1");
}

Important Information for this Arm website

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies. If you are not happy with the use of these cookies, please review our Cookie Policy to learn how they can be disabled. By disabling cookies, some features of the site will not work.