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

Semaphore

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)
 Semaphore (int32_t count, uint16_t max_count)
int32_t wait (uint32_t millisec=osWaitForever)
osStatus release (void)

Semaphore example

Use Semaphore to protect printf().

#include "mbed.h"

Semaphore two_slots(2);
Thread t2;
Thread t3;
    
void test_thread(void const *name) {
    while (true) {
        two_slots.wait();
        printf("%s\n\r", (const char*)name);
        wait(1);
        two_slots.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.