bump standards-version
[gnulib.git] / lib / glthread / thread.c
1 /* Creating and controlling threads.
2    Copyright (C) 2005-2012 Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, see <http://www.gnu.org/licenses/>.  */
16
17 /* Written by Bruno Haible <bruno@clisp.org>, 2005.
18    Based on GCC's gthr-posix.h, gthr-posix95.h, gthr-solaris.h,
19    gthr-win32.h.  */
20
21 #include <config.h>
22
23 /* Specification.  */
24 #include "glthread/thread.h"
25
26 #include <stdlib.h>
27 #include "glthread/lock.h"
28
29 /* ========================================================================= */
30
31 #if USE_POSIX_THREADS
32
33 #include <pthread.h>
34
35 #ifdef PTW32_VERSION
36
37 const gl_thread_t gl_null_thread /* = { .p = NULL } */;
38
39 #endif
40
41 #endif
42
43 /* ========================================================================= */
44
45 #if USE_WINDOWS_THREADS
46
47 #include <process.h>
48
49 /* -------------------------- gl_thread_t datatype -------------------------- */
50
51 /* The Thread-Local Storage (TLS) key that allows to access each thread's
52    'struct gl_thread_struct *' pointer.  */
53 static DWORD self_key = (DWORD)-1;
54
55 /* Initializes self_key.  This function must only be called once.  */
56 static void
57 do_init_self_key (void)
58 {
59   self_key = TlsAlloc ();
60   /* If this fails, we're hosed.  */
61   if (self_key == (DWORD)-1)
62     abort ();
63 }
64
65 /* Initializes self_key.  */
66 static void
67 init_self_key (void)
68 {
69   gl_once_define(static, once)
70   gl_once (once, do_init_self_key);
71 }
72
73 /* This structure contains information about a thread.
74    It is stored in TLS under key self_key.  */
75 struct gl_thread_struct
76 {
77   /* Fields for managing the handle.  */
78   HANDLE volatile handle;
79   CRITICAL_SECTION handle_lock;
80   /* Fields for managing the exit value.  */
81   void * volatile result;
82   /* Fields for managing the thread start.  */
83   void * (*func) (void *);
84   void *arg;
85 };
86
87 /* Return a real HANDLE object for the current thread.  */
88 static inline HANDLE
89 get_current_thread_handle (void)
90 {
91   HANDLE this_handle;
92
93   /* GetCurrentThread() returns a pseudo-handle, i.e. only a symbolic
94      identifier, not a real handle.  */
95   if (!DuplicateHandle (GetCurrentProcess (), GetCurrentThread (),
96                         GetCurrentProcess (), &this_handle,
97                         0, FALSE, DUPLICATE_SAME_ACCESS))
98     abort ();
99   return this_handle;
100 }
101
102 gl_thread_t
103 gl_thread_self_func (void)
104 {
105   gl_thread_t thread;
106
107   if (self_key == (DWORD)-1)
108     init_self_key ();
109   thread = TlsGetValue (self_key);
110   if (thread == NULL)
111     {
112       /* This happens only in threads that have not been created through
113          glthread_create(), such as the main thread.  */
114       for (;;)
115         {
116           thread =
117             (struct gl_thread_struct *)
118             malloc (sizeof (struct gl_thread_struct));
119           if (thread != NULL)
120             break;
121           /* Memory allocation failed.  There is not much we can do.  Have to
122              busy-loop, waiting for the availability of memory.  */
123           Sleep (1);
124         }
125
126       thread->handle = get_current_thread_handle ();
127       InitializeCriticalSection (&thread->handle_lock);
128       thread->result = NULL; /* just to be deterministic */
129       TlsSetValue (self_key, thread);
130     }
131   return thread;
132 }
133
134 /* The main function of a freshly creating thread.  It's a wrapper around
135    the FUNC and ARG arguments passed to glthread_create_func.  */
136 static unsigned int WINAPI
137 wrapper_func (void *varg)
138 {
139   struct gl_thread_struct *thread = (struct gl_thread_struct *)varg;
140
141   EnterCriticalSection (&thread->handle_lock);
142   /* Create a new handle for the thread only if the parent thread did not yet
143      fill in the handle.  */
144   if (thread->handle == NULL)
145     thread->handle = get_current_thread_handle ();
146   LeaveCriticalSection (&thread->handle_lock);
147
148   if (self_key == (DWORD)-1)
149     init_self_key ();
150   TlsSetValue (self_key, thread);
151
152   /* Run the thread.  Store the exit value if the thread was not terminated
153      otherwise.  */
154   thread->result = thread->func (thread->arg);
155   return 0;
156 }
157
158 int
159 glthread_create_func (gl_thread_t *threadp, void * (*func) (void *), void *arg)
160 {
161   struct gl_thread_struct *thread =
162     (struct gl_thread_struct *) malloc (sizeof (struct gl_thread_struct));
163   if (thread == NULL)
164     return ENOMEM;
165   thread->handle = NULL;
166   InitializeCriticalSection (&thread->handle_lock);
167   thread->result = NULL; /* just to be deterministic */
168   thread->func = func;
169   thread->arg = arg;
170
171   {
172     unsigned int thread_id;
173     HANDLE thread_handle;
174
175     thread_handle = (HANDLE)
176       _beginthreadex (NULL, 100000, wrapper_func, thread, 0, &thread_id);
177       /* calls CreateThread with the same arguments */
178     if (thread_handle == NULL)
179       {
180         DeleteCriticalSection (&thread->handle_lock);
181         free (thread);
182         return EAGAIN;
183       }
184
185     EnterCriticalSection (&thread->handle_lock);
186     if (thread->handle == NULL)
187       thread->handle = thread_handle;
188     else
189       /* thread->handle was already set by the thread itself.  */
190       CloseHandle (thread_handle);
191     LeaveCriticalSection (&thread->handle_lock);
192
193     *threadp = thread;
194     return 0;
195   }
196 }
197
198 int
199 glthread_join_func (gl_thread_t thread, void **retvalp)
200 {
201   if (thread == NULL)
202     return EINVAL;
203
204   if (thread == gl_thread_self ())
205     return EDEADLK;
206
207   if (WaitForSingleObject (thread->handle, INFINITE) == WAIT_FAILED)
208     return EINVAL;
209
210   if (retvalp != NULL)
211     *retvalp = thread->result;
212
213   DeleteCriticalSection (&thread->handle_lock);
214   CloseHandle (thread->handle);
215   free (thread);
216
217   return 0;
218 }
219
220 int
221 gl_thread_exit_func (void *retval)
222 {
223   gl_thread_t thread = gl_thread_self ();
224   thread->result = retval;
225   _endthreadex (0); /* calls ExitThread (0) */
226   abort ();
227 }
228
229 #endif
230
231 /* ========================================================================= */