SuperTinyKernel™ RTOS 1.08.x
Lightweight, high-performance, deterministic, bare-metal C++ RTOS for resource-constrained embedded systems. MIT Open Source License.
Loading...
Searching...
No Matches
semaphore.h File Reference

POSIX-named counting semaphores (<semaphore.h>) for STK, backed by stk::sync::SemaphoreT. Implemented by stk_c_pthread.cpp (the same shim as <pthread.h>, no dependency on the STK C API); stk_pthread_bind_kernel() is not required, only a running kernel with KERNEL_SYNC. More...

#include <cstdint>
#include <cstddef>
#include <ctime>
#include <stk_config.h>
Include dependency graph for semaphore.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  sem_t
 A POSIX counting semaphore. More...

Macros

#define STK_SYNC_DEBUG_NAMES   (0)
#define CLOCK_REALTIME   (0)
#define CLOCK_MONOTONIC   (1)
#define SEM_VALUE_MAX   (2147483647)
 Maximum value of a semaphore (the counter is 32-bit, POSIX requires at least 32767).
#define STK_C_SEM_WORDS
 Size (in machine words) of the opaque storage of a sem_t: the C++ object (7 words + 1 with debug names) plus two 32-bit counters and alignment slack. Verified at compile time against sizeof() of the real object by stk_c_pthread.cpp.
#define __stk_sem_aligned

Typedefs

typedef struct sem_t sem_t
 A POSIX counting semaphore.

Functions

int sem_init (sem_t *sem, int pshared, unsigned int value)
 Initialize an unnamed semaphore.
int sem_destroy (sem_t *sem)
 Destroy a semaphore.
int sem_wait (sem_t *sem)
 Take a token, blocking until one is available.
int sem_trywait (sem_t *sem)
 Take a token without blocking.
int sem_timedwait (sem_t *sem, const struct timespec *abstime)
 Take a token, waiting until the absolute deadline abstime.
int sem_clockwait (sem_t *sem, clockid_t clock_id, const struct timespec *abstime)
 sem_timedwait() with an explicit clock (POSIX.1-2024).
int sem_post (sem_t *sem)
 Release a token (wakes the first waiter, otherwise increments the count).
int sem_getvalue (sem_t *sem, int *sval)
 Get the current count.

Detailed Description

POSIX-named counting semaphores (<semaphore.h>) for STK, backed by stk::sync::SemaphoreT. Implemented by stk_c_pthread.cpp (the same shim as <pthread.h>, no dependency on the STK C API); stk_pthread_bind_kernel() is not required, only a running kernel with KERNEL_SYNC.

Unnamed semaphores only: sem_init/destroy/wait/trywait/timedwait/clockwait/post/getvalue. Named semaphores (sem_open/close/unlink) are not provided, STK has no named kernel objects.

Like POSIX, the functions return 0 on success and -1 on failure with errno set:

  • sem_wait(): EINTR if the wait was cancelled via IKernel::CancelTaskWait(), retry as for a signal.
  • sem_trywait(): EAGAIN if the count is zero.
  • sem_timedwait()/sem_clockwait(): ETIMEDOUT, or EINVAL for an invalid timeout. The deadline is interpreted on the STK tick timeline (see "timedwait limitation" in stk_c_pthread.h) and is rounded up to whole ticks. A token which is available is always taken, even if the deadline has already passed.
  • sem_post(): EOVERFLOW if the count is already SEM_VALUE_MAX and nobody is waiting.
  • sem_init(): EINVAL if the value exceeds SEM_VALUE_MAX, ENOSYS if pshared is non-zero.

Definition in file semaphore.h.

Macro Definition Documentation

◆ __stk_sem_aligned

#define __stk_sem_aligned

Definition at line 80 of file semaphore.h.

◆ CLOCK_MONOTONIC

#define CLOCK_MONOTONIC   (1)

Definition at line 57 of file semaphore.h.

Referenced by stk::pthread::IsSupportedClock().

◆ CLOCK_REALTIME

#define CLOCK_REALTIME   (0)

Definition at line 54 of file semaphore.h.

Referenced by stk::pthread::IsSupportedClock(), pthread_condattr_init(), and timespec_get().

◆ SEM_VALUE_MAX

#define SEM_VALUE_MAX   (2147483647)

Maximum value of a semaphore (the counter is 32-bit, POSIX requires at least 32767).

Definition at line 67 of file semaphore.h.

Referenced by sem_init(), and sysconf().

◆ STK_C_SEM_WORDS

#define STK_C_SEM_WORDS
Value:
(7U + (STK_SYNC_DEBUG_NAMES ? 1U : 0U) + \
((2U * sizeof(uint32_t) + sizeof(uintptr_t) - 1U) / sizeof(uintptr_t)) + 1U)
#define STK_SYNC_DEBUG_NAMES
Enable debug names for synchronization primitives (mutexes, events, etc.) for debugging and tracing p...
Definition stk_defs.h:239

Size (in machine words) of the opaque storage of a sem_t: the C++ object (7 words + 1 with debug names) plus two 32-bit counters and alignment slack. Verified at compile time against sizeof() of the real object by stk_c_pthread.cpp.

Definition at line 74 of file semaphore.h.

74#define STK_C_SEM_WORDS (7U + (STK_SYNC_DEBUG_NAMES ? 1U : 0U) + \
75 ((2U * sizeof(uint32_t) + sizeof(uintptr_t) - 1U) / sizeof(uintptr_t)) + 1U)

◆ STK_SYNC_DEBUG_NAMES

#define STK_SYNC_DEBUG_NAMES   (0)

Definition at line 49 of file semaphore.h.

Typedef Documentation

◆ sem_t

typedef struct sem_t sem_t

A POSIX counting semaphore.

Note
Fields are considered private. There is no static initializer (as in POSIX): use sem_init().

Function Documentation

◆ sem_clockwait()

int sem_clockwait ( sem_t * sem,
clockid_t clock_id,
const struct timespec * abstime )

sem_timedwait() with an explicit clock (POSIX.1-2024).

Parameters
[in]clock_idCLOCK_REALTIME or CLOCK_MONOTONIC, both refer to the same STK tick timeline.
Returns
As sem_timedwait(), EINVAL for any other clock.

Definition at line 2930 of file stk_c_pthread.cpp.

2931{
2932 return IsSupportedClock(clock_id) ? sem_timedwait(sem, abstime) : SemFail(EINVAL);
2933}
static int SemFail(int err)
int sem_timedwait(sem_t *sem, const struct timespec *abstime)
Take a token, waiting until the absolute deadline abstime.
static bool IsSupportedClock(clockid_t clock_id)

References stk::pthread::IsSupportedClock(), sem_timedwait(), and SemFail().

Here is the call graph for this function:

◆ sem_destroy()

int sem_destroy ( sem_t * sem)

Destroy a semaphore.

Warning
No task may be waiting on it.
Returns
0 on success, -1 with errno = EINVAL if sem is NULL or not initialized.

Definition at line 2881 of file stk_c_pthread.cpp.

2882{
2883 int result;
2884
2885 if (!IsSemReady(sem))
2886 {
2887 result = SemFail(EINVAL);
2888 }
2889 else
2890 {
2891 SemOf(sem)->~PosixSemaphore();
2892 sem->__handle = nullptr;
2893 result = 0;
2894 }
2895
2896 return result;
2897}
static bool IsSemReady(const sem_t *sem)
static PosixSemaphore * SemOf(sem_t *o)
void * __handle
NULL until sem_init(), then points into __mem.
Definition semaphore.h:91

References sem_t::__handle, IsSemReady(), SemFail(), and SemOf().

Here is the call graph for this function:

◆ sem_getvalue()

int sem_getvalue ( sem_t * sem,
int * sval )

Get the current count.

Parameters
[out]svalReceives the count (0 if tasks are waiting, STK does not report negative values).
Returns
0 on success, -1 with errno = EINVAL.
Note
ISR-safe. The value may be stale as soon as it is returned.

Definition at line 2952 of file stk_c_pthread.cpp.

2953{
2954 int result;
2955
2956 if (!IsSemReady(sem) || (sval == nullptr))
2957 {
2958 result = SemFail(EINVAL);
2959 }
2960 else
2961 {
2962 *sval = static_cast<int>(SemOf(sem)->GetCount());
2963 result = 0;
2964 }
2965
2966 return result;
2967}
T GetCount() const
Get current counter value.

References stk::sync::SemaphoreT< T >::GetCount(), IsSemReady(), SemFail(), and SemOf().

Here is the call graph for this function:

◆ sem_init()

int sem_init ( sem_t * sem,
int pshared,
unsigned int value )

Initialize an unnamed semaphore.

Parameters
[in]semSemaphore to initialize.
[in]psharedMust be 0 (process-shared semaphores are not supported).
[in]valueInitial count, at most SEM_VALUE_MAX.
Returns
0 on success, -1 with errno = EINVAL (NULL sem or value too large) or ENOSYS (pshared != 0).

Definition at line 2855 of file stk_c_pthread.cpp.

2856{
2857 int result;
2858
2859 if (sem == nullptr)
2860 {
2861 result = SemFail(EINVAL);
2862 }
2863 else if (pshared != 0)
2864 {
2865 result = SemFail(ENOSYS); // process-shared semaphores are not supported
2866 }
2867 else if (value > static_cast<unsigned int>(SEM_VALUE_MAX))
2868 {
2869 result = SemFail(EINVAL);
2870 }
2871 else
2872 {
2873 sem->__handle = ConstructIn<PosixSemaphore>(sem->__mem, static_cast<uint32_t>(value),
2874 static_cast<uint32_t>(SEM_VALUE_MAX));
2875 result = 0;
2876 }
2877
2878 return result;
2879}
#define SEM_VALUE_MAX
Maximum value of a semaphore (the counter is 32-bit, POSIX requires at least 32767).
Definition semaphore.h:67
static T * ConstructIn(Mem &mem, Args &&... args)
Construct object T in-place inside a C memory container.
Definition stk_c.h:2970
struct sem_t::@301215357362074031213040000172073175337057334267 __mem
In-place storage of the C++ semaphore.

References sem_t::__handle, sem_t::__mem, stk::ConstructIn(), SEM_VALUE_MAX, and SemFail().

Here is the call graph for this function:

◆ sem_post()

int sem_post ( sem_t * sem)

Release a token (wakes the first waiter, otherwise increments the count).

Returns
0 on success, -1 with errno = EOVERFLOW if the count is at SEM_VALUE_MAX, or EINVAL.
Note
ISR-safe.

Definition at line 2935 of file stk_c_pthread.cpp.

2936{
2937 int result;
2938
2939 if (!IsSemReady(sem))
2940 {
2941 result = SemFail(EINVAL);
2942 }
2943 else
2944 {
2945 // TrySignal() fails (without asserting) if the count is at its maximum and nobody is waiting
2946 result = SemOf(sem)->TrySignal() ? 0 : SemFail(EOVERFLOW);
2947 }
2948
2949 return result;
2950}
bool TrySignal()
Try to post a signal without exceeding max_count.

References IsSemReady(), SemFail(), SemOf(), and stk::sync::SemaphoreT< T >::TrySignal().

Here is the call graph for this function:

◆ sem_timedwait()

int sem_timedwait ( sem_t * sem,
const struct timespec * abstime )

Take a token, waiting until the absolute deadline abstime.

Returns
0 on success, -1 with errno = ETIMEDOUT, EINVAL or EINTR.
Warning
ISR-unsafe.

Definition at line 2911 of file stk_c_pthread.cpp.

2912{
2913 int result;
2914
2916
2917 if (!IsSemReady(sem) || !IsValidTimespec(abstime))
2918 {
2919 result = SemFail(EINVAL);
2920 }
2921 else
2922 {
2923 // a deadline in the past is a non-blocking attempt: an available token is still taken (POSIX)
2924 result = SemWaitResult(SemOf(sem)->WaitEx(TimespecToRelativeTimeout(abstime)), ETIMEDOUT);
2925 }
2926
2927 return result;
2928}
static int SemWaitResult(EWaitResult wr, int timeout_errno)
static Timeout TimespecToRelativeTimeout(const struct timespec *abstime)
static bool IsValidTimespec(const struct timespec *ts)
static void TestCancelPoint()

References IsSemReady(), stk::pthread::IsValidTimespec(), SemFail(), SemOf(), SemWaitResult(), stk::pthread::TestCancelPoint(), and stk::pthread::TimespecToRelativeTimeout().

Referenced by sem_clockwait().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ sem_trywait()

int sem_trywait ( sem_t * sem)

Take a token without blocking.

Returns
0 on success, -1 with errno = EAGAIN if the count is zero, or EINVAL.
Note
ISR-safe.

Definition at line 2906 of file stk_c_pthread.cpp.

2907{
2908 return IsSemReady(sem) ? SemWaitResult(SemOf(sem)->WaitEx(NO_WAIT), EAGAIN) : SemFail(EINVAL);
2909}
static constexpr Timeout NO_WAIT
Timeout value: return immediately if the synchronization object is not yet signaled (non-blocking pol...
Definition stk_common.h:280

References IsSemReady(), stk::NO_WAIT, SemFail(), SemOf(), and SemWaitResult().

Here is the call graph for this function:

◆ sem_wait()

int sem_wait ( sem_t * sem)

Take a token, blocking until one is available.

Returns
0 on success, -1 with errno = EINVAL, or EINTR if the wait was cancelled (retry).
Warning
ISR-unsafe.

Definition at line 2899 of file stk_c_pthread.cpp.

2900{
2902
2903 return IsSemReady(sem) ? SemWaitResult(SemOf(sem)->WaitEx(WAIT_INFINITE), EINVAL) : SemFail(EINVAL);
2904}
static constexpr Timeout WAIT_INFINITE
Timeout value: block indefinitely until the synchronization object is signaled.
Definition stk_common.h:274

References IsSemReady(), SemFail(), SemOf(), SemWaitResult(), stk::pthread::TestCancelPoint(), and stk::WAIT_INFINITE.

Here is the call graph for this function: