da9a6adf3def39d5519c202a2f21733f5c752c86
[fishladder.git] / vg / vg_platform.h
1 // Copyright (C) 2021 Harry Godden (hgn) - All Rights Reserved
2
3 typedef uint8_t u8;
4 typedef uint16_t u16;
5 typedef uint32_t u32;
6 typedef uint64_t u64;
7 typedef int8_t i8;
8 typedef int16_t i16;
9 typedef int32_t i32;
10 typedef int64_t i64;
11
12 typedef unsigned int uint;
13
14 #define vg_min( A, B ) ((A)<(B)?(A):(B))
15 #define vg_max( A, B ) ((A)>(B)?(A):(B))
16 #define vg_list_size( A ) (sizeof(A)/sizeof(A[0]))
17
18 // THREADING
19 // ==================================================================================================================
20
21 // Pthred emulation for windows
22 #ifdef _WIN32
23 #include <windows.h>
24 #define MUTEX_TYPE HANDLE
25 #define MUTEX_INITIALIZER NULL
26 #define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL)
27 #define MUTEX_CLEANUP(x) (CloseHandle(x)) //TODO: Why is this defined but never used?
28 #define MUTEX_LOCK(x) emulate_pthread_mutex_lock(&(x))
29 #define MUTEX_UNLOCK(x) (ReleaseMutex(x))
30
31 int emulate_pthread_mutex_lock( volatile MUTEX_TYPE *mx )
32 {
33 if( *mx == NULL ) /* static initializer? */
34 {
35 HANDLE p = CreateMutex( NULL, FALSE, NULL );
36 if( InterlockedCompareExchangePointer( (PVOID*)mx, (PVOID)p, NULL ) != NULL )
37 CloseHandle(p);
38 }
39
40 return WaitForSingleObject( *mx, INFINITE ) == WAIT_FAILED;
41 }
42 #else
43 #include <pthread.h>
44 #define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
45 #define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
46 #define MUTEX_TYPE pthread_mutex_t
47 #define MUTEX_INITIALIZER {0}
48 #endif
49
50
51 int vg_thread_run( void *pfunc, void *data )
52 {
53 #ifdef _WIN32
54
55 HANDLE hThread = CreateThread
56 (
57 NULL, // Thread attributes
58 0, // Stack size (0 = use default)
59 pfunc, // Thread start address
60 data, // Parameter to pass to the thread
61 0, // Creation flags
62 NULL // Thread id
63 );
64
65 if ( hThread == NULL )
66 {
67 // Thread creation failed.
68 // More details can be retrieved by calling GetLastError()
69 return 1;
70 }
71 else
72 {
73 CloseHandle( hThread );
74 return 0;
75 }
76
77 #else
78
79 pthread_t hThread;
80 if( pthread_create( &hThread, NULL, pfunc, data ) )
81 {
82 return 1;
83 }
84 else
85 {
86 pthread_detach( hThread );
87 return 0;
88 }
89
90 #endif
91 }