medfall

A super great game engine
Log | Files | Refs

unix_thread.h (1173B)


      1 #pragma once
      2 
      3 #include <err.h>
      4 #include <pthread.h>
      5 #include <unistd.h>
      6 #include <sys/syscall.h>
      7 
      8 #include "platform.h"
      9 #include "intrinsics.h"
     10 
     11 #define THREAD( f ) void * f( void * data )
     12 typedef THREAD( ThreadCallback );
     13 #define THREAD_END return NULL
     14 
     15 struct Thread {
     16 	pthread_t pthread;
     17 };
     18 
     19 inline void thread_init( Thread * thread, ThreadCallback callback, void * data ) {
     20 	const int ok = pthread_create( &thread->pthread, NULL, callback, data );
     21 	if( ok == -1 ) {
     22 		err( 1, "pthread_create failed" );
     23 	}
     24 }
     25 
     26 inline u64 thread_getid() {
     27 #if PLATFORM_LINUX
     28 	return checked_cast< u64 >( pthread_self() );
     29 #elif PLATFORM_OPENBSD
     30 	return checked_cast< u64 >( getthrid() );
     31 #elif PLATFORM_OSX
     32 	u64 id;
     33 	pthread_threadid_np( NULL, &id );
     34 	return id;
     35 #else
     36 #error new platform
     37 #endif
     38 }
     39 
     40 inline void thread_join( Thread * thread ) {
     41 	int ok = pthread_join( thread->pthread, NULL );
     42 	if( ok == -1 ) {
     43 		err( 1, "pthread_join failed" );
     44 	}
     45 }
     46 
     47 inline void thread_yield() {
     48 #if PLATFORM_LINUX
     49 	int ok = pthread_yield();
     50 	if( ok == -1 ) {
     51 		err( 1, "pthread_yield" );
     52 	}
     53 #elif PLATFORM_OSX
     54 	sched_yield();
     55 #elif PLATFORM_OPENBSD
     56 	pthread_yield();
     57 #else
     58 #error new platform
     59 #endif
     60 }