Non-threaded build fix
[p5sagit/p5-mst-13.2.git] / win32 / win32thread.c
1 #include "EXTERN.h"
2 #include "perl.h"
3
4 #ifdef USE_DECLSPEC_THREAD
5 __declspec(thread) struct perl_thread *Perl_current_thread = NULL;
6 #endif
7
8 void
9 Perl_setTHR(struct perl_thread *t)
10 {
11 #ifdef USE_THREADS
12 #ifdef USE_DECLSPEC_THREAD
13  Perl_current_thread = t;
14 #else
15  TlsSetValue(thr_key,t);
16 #endif
17 #endif
18 }
19
20 struct perl_thread *
21 Perl_getTHR(void)
22 {
23 #ifdef USE_THREADS
24 #ifdef USE_DECLSPEC_THREAD
25  return Perl_current_thread;
26 #else
27  return (struct perl_thread *) TlsGetValue(thr_key);
28 #endif
29 #else
30  return NULL;
31 #endif
32 }
33
34 void
35 Perl_alloc_thread_key(void)
36 {
37 #ifdef USE_THREADS
38     static int key_allocated = 0;
39     if (!key_allocated) {
40         if ((thr_key = TlsAlloc()) == TLS_OUT_OF_INDEXES)
41             croak("panic: TlsAlloc");
42         key_allocated = 1;
43     }
44 #endif
45 }
46
47 void
48 Perl_set_thread_self(struct perl_thread *thr)
49 {
50 #ifdef USE_THREADS
51     /* Set thr->self.  GetCurrentThread() retrurns a pseudo handle, need
52        this to convert it into a handle another thread can use.
53      */
54     DuplicateHandle(GetCurrentProcess(),
55                     GetCurrentThread(),
56                     GetCurrentProcess(),
57                     &thr->self,
58                     0,
59                     FALSE,
60                     DUPLICATE_SAME_ACCESS);
61 #endif
62 }
63
64 #ifdef USE_THREADS
65 int
66 Perl_thread_create(struct perl_thread *thr, thread_func_t *fn)
67 {
68     DWORD junk;
69
70     MUTEX_LOCK(&thr->mutex);
71     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
72                           "%p: create OS thread\n", thr));
73     thr->self = CreateThread(NULL, 0, fn, (void*)thr, 0, &junk);
74     DEBUG_L(PerlIO_printf(PerlIO_stderr(),
75                           "%p: OS thread = %p, id=%ld\n", thr, thr->self, junk));
76     MUTEX_UNLOCK(&thr->mutex);
77     return thr->self ? 0 : -1;
78 }
79 #endif