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... | |
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_for (Kernel::Clock::duration_u32 rel_time) |
Wait until a Semaphore resource becomes available. More... | |
bool | try_acquire_until (uint64_t millisec) |
Wait until a Semaphore resource becomes available. More... | |
bool | try_acquire_until (Kernel::Clock::time_point abs_time) |
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().
/*
* Copyright (c) 2020 Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*/
#include "mbed.h"
Semaphore one_slot(1);
Thread t2;
Thread t3;
void test_thread(void const *name)
{
while (true) {
one_slot.acquire();
printf("%s\n\r", (const char *)name);
ThisThread::sleep_for(1000);
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");
}