2222 * THE SOFTWARE.
2323 ******************************************************************************/
2424
25+ #include " common/common.h"
2526#include " os/os_specific.h"
2627
28+ #include < errno.h>
29+ #include < pthread.h>
30+ #include < semaphore.h>
2731#include < time.h>
2832#include < unistd.h>
2933
@@ -41,4 +45,77 @@ uint64_t Timing::GetTick()
4145
4246void Threading::SetCurrentThreadName (const rdcstr &name)
4347{
48+ pthread_setname_np (pthread_self (), name.c_str ());
4449}
50+
51+ uint32_t Threading::NumberOfCores ()
52+ {
53+ long ret = sysconf (_SC_NPROCESSORS_ONLN);
54+ if (ret <= 0 )
55+ return 1 ;
56+ return uint32_t (ret);
57+ }
58+
59+ namespace Threading
60+ {
61+
62+ // works for all posix except apple, hence being here
63+ struct PosixSemaphore : public Semaphore
64+ {
65+ ~PosixSemaphore () {}
66+
67+ sem_t h;
68+ };
69+
70+ Semaphore *Semaphore::Create ()
71+ {
72+ PosixSemaphore *sem = new PosixSemaphore ();
73+ int err = sem_init (&sem->h , 0 , 0 );
74+ // only documented errors are too large initial value (impossible for 0) or for shared semaphores
75+ // going wrong (we're not shared)
76+ RDCASSERT (err == 0 , (int )errno);
77+ return sem;
78+ }
79+
80+ void Semaphore::Destroy ()
81+ {
82+ PosixSemaphore *sem = (PosixSemaphore *)this ;
83+ sem_destroy (&sem->h );
84+ delete sem;
85+ }
86+
87+ void Semaphore::Wake (uint32_t numToWake)
88+ {
89+ PosixSemaphore *sem = (PosixSemaphore *)this ;
90+ for (uint32_t i = 0 ; i < numToWake; i++)
91+ sem_post (&sem->h );
92+ }
93+
94+ void Semaphore::WaitForWake ()
95+ {
96+ PosixSemaphore *sem = (PosixSemaphore *)this ;
97+
98+ while (true )
99+ {
100+ int ret = sem_wait (&sem->h );
101+
102+ if (ret == 0 )
103+ return ;
104+
105+ if (errno == EINTR)
106+ continue ;
107+
108+ RDCWARN (" Semaphore wait failed: %d" , errno);
109+ return ;
110+ }
111+ }
112+
113+ Semaphore::Semaphore ()
114+ {
115+ }
116+
117+ Semaphore::~Semaphore ()
118+ {
119+ }
120+
121+ } // namespace Threading
0 commit comments