Merge branch 'master' of git://cadel.mutabah.net/acess2
[tpg/acess2.git] / AcessNative / acesskernel_src / threads_glue.c
1 /*
2  * Acess2 Native Kernel
3  * - Acess kernel emulation on another OS using SDL and UDP
4  *
5  * threads.c
6  * - Thread and process handling
7  */
8 #include "include/threads_glue.h"
9
10 #define _ACESS_H
11 typedef void    **tShortSpinlock;
12 #include <rwlock.h>
13
14 // - Native headers
15 #include <unistd.h>
16 #include <sys/types.h>
17 #include <stdint.h>
18 //#include "/usr/include/signal.h"
19 #include <SDL/SDL.h>
20 #include <pthread.h>
21 #include <assert.h>
22
23 #include <logdebug.h>   // Kernel land, but uses standards
24
25 // === CODE ===
26 void Threads_Glue_Yield(void)
27 {
28         SDL_Delay(10);
29 }
30
31 void Threads_Glue_AcquireMutex(void **Lock)
32 {
33         if(!*Lock) {
34                 *Lock = malloc( sizeof(pthread_mutex_t) );
35                 pthread_mutex_init( *Lock, NULL );
36         }
37         pthread_mutex_lock( *Lock );
38 }
39
40 void Threads_Glue_ReleaseMutex(void **Lock)
41 {
42         pthread_mutex_unlock( *Lock );
43 }
44
45 void Threads_Glue_SemInit(void **Ptr, int Val)
46 {
47         *Ptr = SDL_CreateSemaphore(Val);
48         if( !*Ptr ) {
49                 Log_Warning("Threads", "Semaphore creation failed - %s", SDL_GetError());
50         }
51 }
52
53 int Threads_Glue_SemWait(void *Ptr, int Max)
54 {
55          int    have = 0;
56         assert(Ptr);
57         do {
58                 if( SDL_SemWait( Ptr ) == -1 ) {
59                         return -1;
60                 }
61                 have ++;
62         } while( SDL_SemValue(Ptr) && have < Max );
63         return have;
64 }
65
66 int Threads_Glue_SemSignal( void *Ptr, int AmmountToAdd )
67 {
68          int    i;
69         for( i = 0; i < AmmountToAdd; i ++ )
70                 SDL_SemPost( Ptr );
71         return AmmountToAdd;
72 }
73
74 // --------------------------------------------------------------------
75 // Event handling
76 // --------------------------------------------------------------------
77 int RWLock_AcquireRead(tRWLock *Lock)
78 {
79         if( !Lock->ReaderWaiting ) {
80                 Lock->ReaderWaiting = malloc(sizeof(pthread_rwlock_t));
81                 pthread_rwlock_init( (void*)Lock->ReaderWaiting, 0 );
82         }
83         pthread_rwlock_rdlock( (void*)Lock->ReaderWaiting );
84         return 0;
85 }
86 int RWLock_AcquireWrite(tRWLock *Lock)
87 {
88         if( !Lock->ReaderWaiting ) {
89                 Lock->ReaderWaiting = malloc(sizeof(pthread_rwlock_t));
90                 pthread_rwlock_init( (void*)Lock->ReaderWaiting, 0 );
91         }
92         pthread_rwlock_wrlock( (void*)Lock->ReaderWaiting );
93         return 0;
94 }
95 void RWLock_Release(tRWLock *Lock)
96 {
97         pthread_rwlock_unlock( (void*)Lock->ReaderWaiting );
98 }
99

UCC git Repository :: git.ucc.asn.au