Stroika Library 3.0d16
 
Loading...
Searching...
No Matches
SemWaitableEvent.cpp
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2025. All rights reserved
3 */
4#include "Stroika/Foundation/StroikaPreComp.h"
5
6#include <unistd.h>
7
8#include "Stroika/Foundation/Execution/Exceptions.h"
9
10#include "SemWaitableEvent.h"
11
12using namespace Stroika::Foundation;
13using namespace Stroika::Foundation::Execution;
15
16// Comment this in to turn on aggressive noisy DbgTrace in this module
17//#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1
18
19/*
20 ********************************************************************************
21 ************* Execution::Platform::POSIX::SemWaitableEvent *********************
22 ********************************************************************************
23 */
24SemWaitableEvent::SemWaitableEvent ()
25{
26 [[maybe_unused]] constexpr int kpshared = 0; // shared between threads of a process
27 int defaultValue = 0;
28#if qCompilerAndStdLib_unnamed_semaphores_Buggy
29 char nameBuf[1000] = "/tmp/semaphore-XXXXXX";
30 ::close (::mkstemp (nameBuf)); // create file as side-effect so no race - file name still reserved by this CTOR
31 Verify ((fSem_ = ::sem_open (nameBuf, O_CREAT, S_IRWXU | S_IRWXG, defaultValue)) != SEM_FAILED);
32 Verify (::sem_unlink (nameBuf) == 0);
33#else
34 Verify (::sem_init (&fSem_, kpshared, defaultValue) == 0);
35#endif
36}
37
38SemWaitableEvent::~SemWaitableEvent ()
39{
40#if qCompilerAndStdLib_unnamed_semaphores_Buggy
41 Verify (::sem_close (fSem_) == 0);
42#else
43 Verify (::sem_destroy (&fSem_) == 0);
44#endif
45}
46
48{
49#if qCompilerAndStdLib_unnamed_semaphores_Buggy
50 sem_t* pSem = fSem_;
51#else
52 sem_t* pSem = &fSem_;
53#endif
54 int s{};
55 while ((s = ::sem_wait (pSem)) == -1 && errno == EINTR) {
56 continue; /* Restart if interrupted by handler */
57 }
59}
60
61// use no_sanitize(thread) to workaround http://stroika-bugs.sophists.com/browse/STK-677
62Stroika_Foundation_Debug_ATTRIBUTE_NO_SANITIZE_THREAD void SemWaitableEvent::Set ()
63{
64#if qCompilerAndStdLib_unnamed_semaphores_Buggy
65 sem_t* pSem = fSem_;
66#else
67 sem_t* pSem = &fSem_;
68#endif
69 // see http://stroika-bugs.sophists.com/browse/STK-677 - save/restore errno so this doesn't spoil errno if called from signal handler
70 errno_t saved = errno;
71 Verify (::sem_post (pSem) == 0);
72 errno = saved;
73}
#define Verify(c)
Definition Assertions.h:419
INT_TYPE ThrowPOSIXErrNoIfNegative(INT_TYPE returnCode)