medfall

A super great game engine
Log | Files | Refs

platform_semaphore.h (990B)


      1 #pragma once
      2 
      3 #include "platform.h"
      4 #include "platform_atomic.h"
      5 
      6 #if PLATFORM_WINDOWS
      7 #include "win32_semaphore.h"
      8 #elif PLATFORM_OSX
      9 #include "darwin_semaphore.h"
     10 #elif PLATFORM_UNIX
     11 #include "unix_semaphore.h"
     12 #else
     13 #error new platform
     14 #endif
     15 
     16 struct Semaphore {
     17 	PlatformSemaphore sem;
     18 	// when n < 0, n = - number of waiting threads
     19 	// when n >= 0, n = number of tasks remaining
     20 	atomic_s32 n;
     21 };
     22 
     23 inline void semaphore_init( Semaphore * sem ) {
     24 	platform_semaphore_init( &sem->sem );
     25 	store_release( &sem->n, 0 );
     26 }
     27 
     28 inline void semaphore_signal( Semaphore * sem ) {
     29 	// if n was < 0, wake up a waiting thread
     30 	if( fetch_add_acqrel( &sem->n, 1 ) < 0 ) {
     31 		platform_semaphore_signal( &sem->sem );
     32 	}
     33 }
     34 
     35 inline void semaphore_wait( Semaphore * sem ) {
     36 	// if n is now < 0, put this thread to sleep
     37 	if( fetch_add_acqrel( &sem->n, -1 ) <= 0 ) {
     38 		platform_semaphore_wait( &sem->sem );
     39 	}
     40 }
     41 
     42 inline void semaphore_destroy( Semaphore * sem ) {
     43 	platform_semaphore_destroy( &sem->sem );
     44 }