]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/threadlib.c
Modified Files:
[simgear.git] / simgear / nasal / threadlib.c
1 #ifdef _WIN32
2 #include <windows.h>
3 #else
4 #include <pthread.h>
5 #endif
6
7 #include "data.h"
8 #include "code.h"
9
10 static void lockDestroy(void* lock) { naFreeLock(lock); }
11 static naGhostType LockType = { lockDestroy };
12
13 static void semDestroy(void* sem) { naFreeSem(sem); }
14 static naGhostType SemType = { semDestroy };
15
16 typedef struct {
17     naContext ctx;
18     naRef func;
19 } ThreadData;
20
21 #ifdef _WIN32
22 static DWORD WINAPI threadtop(LPVOID param)
23 #else
24 static void* threadtop(void* param)
25 #endif
26 {
27     ThreadData* td = param;
28     naCall(td->ctx, td->func, 0, 0, naNil(), naNil());
29     naFreeContext(td->ctx);
30     naFree(td);
31     return 0;
32 }
33
34 static naRef f_newthread(naContext c, naRef me, int argc, naRef* args)
35 {
36     ThreadData *td;
37     if(argc < 1 || !naIsFunc(args[0]))
38         naRuntimeError(c, "bad/missing argument to newthread");
39     td = naAlloc(sizeof(*td));
40     td->ctx = naNewContext();
41     td->func = args[0];
42     naTempSave(td->ctx, td->func);
43 #ifdef _WIN32
44     CreateThread(0, 0, threadtop, td, 0, 0);
45 #else
46     { pthread_t t; pthread_create(&t, 0, threadtop, td); }
47 #endif
48     return naNil();
49 }
50
51 static naRef f_newlock(naContext c, naRef me, int argc, naRef* args)
52 {
53     return naNewGhost(c, &LockType, naNewLock());
54 }
55
56 static naRef f_lock(naContext c, naRef me, int argc, naRef* args)
57 {
58     if(argc > 0 && naGhost_type(args[0]) == &LockType)
59         naLock(naGhost_ptr(args[0]));
60     return naNil();
61 }
62
63 static naRef f_unlock(naContext c, naRef me, int argc, naRef* args)
64 {
65     if(argc > 0 && naGhost_type(args[0]) == &LockType)
66         naUnlock(naGhost_ptr(args[0]));
67     return naNil();
68 }
69
70 static naRef f_newsem(naContext c, naRef me, int argc, naRef* args)
71 {
72     return naNewGhost(c, &SemType, naNewSem());
73 }
74
75 static naRef f_semdown(naContext c, naRef me, int argc, naRef* args)
76 {
77     if(argc > 0 && naGhost_type(args[0]) == &SemType)
78         naSemDown(naGhost_ptr(args[0]));
79     return naNil();
80 }
81
82 static naRef f_semup(naContext c, naRef me, int argc, naRef* args)
83 {
84     if(argc > 0 && naGhost_type(args[0]) == &SemType)
85         naSemUp(naGhost_ptr(args[0]), 1);
86     return naNil();
87 }
88
89 static naCFuncItem funcs[] = {
90     { "newthread", f_newthread },
91     { "newlock", f_newlock },
92     { "lock", f_lock },
93     { "unlock", f_unlock },
94     { "newsem", f_newsem },
95     { "semdown", f_semdown },
96     { "semup", f_semup },
97     { 0 }
98 };
99
100 naRef naInit_thread(naContext c)
101 {
102     return naGenLib(c, funcs);
103 }