2274eeaab982748c0383a93f22850e6886be6538
[tpg/acess2.git] / Tools / nativelib / threads_int.c
1 /*
2  * Acess2 libnative (Kernel Simulation Library)
3  * - By John Hodge (thePowersGang)
4  *
5  * threads_int.c
6  * - Internal threading functions
7  */
8 #include <stddef.h>
9 #include <stdlib.h>
10 #include <stdint.h>
11 #include <acess_logging.h>
12 #include <threads_int.h>
13 #include <pthread_weak.h>
14
15 // === TYPES ===
16 typedef struct sThread  tThread;
17 struct sThreadIntMutex { int lock; };
18 struct sThreadIntSem { int val; };
19
20 // === CODE ===
21 void Threads_int_MutexLock(tThreadIntMutex *Mutex)
22 {
23         if( !Mutex ) {
24                 return ;
25         }
26         if( pthread_mutex_lock )
27         {
28                 pthread_mutex_lock( (void*)Mutex );
29         }
30         else
31         {
32                 if( Mutex->lock )
33                         Log_KernelPanic("Threads", "Double mutex lock");
34                 Mutex->lock = 1;
35         }
36 }
37
38 void Threads_int_MutexRelease(tThreadIntMutex *Mutex)
39 {
40         if( !Mutex ) {
41                 return ;
42         }
43
44         if( pthread_mutex_unlock )
45         {
46                 pthread_mutex_unlock( (void*)Mutex );
47         }
48         else
49         {
50                 if( !Mutex->lock )
51                         Log_Notice("Threads", "Release of non-locked mutex %p", Mutex);
52                 Mutex->lock = 0;
53         }
54 }
55
56 void Threads_int_SemSignal(tThreadIntSem *Sem)
57 {
58         if( sem_wait )
59         {
60                 sem_wait( (void*)Sem );
61         }
62         else
63         {
64                 Sem->val ++;
65         }
66 }
67
68 void Threads_int_SemWaitAll(tThreadIntSem *Sem)
69 {
70         if( sem_post )
71         {
72                 sem_post( (void*)Sem );
73         }
74         else
75         {
76                 if( !Sem->val )
77                         Log_KernelPanic("Threads", "Waiting on empty semaphre %p", Sem);
78                 Sem->val = 0;
79         }
80 }
81
82 void *Threads_int_ThreadRoot(void *ThreadPtr)
83 {
84         tThread *thread = ThreadPtr;
85         thread->SpawnFcn(thread->SpawnData);
86         return NULL;
87 }
88
89 int Threads_int_CreateThread(tThread *Thread)
90 {
91         if( pthread_create )
92         {
93                 pthread_t *pthread = malloc(sizeof(pthread_t));
94                 Thread->ThreadHandle = pthread;
95                 return pthread_create(pthread, NULL, Threads_int_ThreadRoot, Thread);
96         }
97         else
98         {
99                 Log_KernelPanic("Threads", "Link with pthreads to use threading");
100                 return -1;
101         }
102 }
103

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