Python-2.7.3/Python/thread.c

No issues found

  1 /* Thread package.
  2    This is intended to be usable independently from Python.
  3    The implementation for system foobar is in a file thread_foobar.h
  4    which is included by this file dependent on config settings.
  5    Stuff shared by all thread_*.h files is collected here. */
  6 
  7 #include "Python.h"
  8 
  9 
 10 #ifndef _POSIX_THREADS
 11 /* This means pthreads are not implemented in libc headers, hence the macro
 12    not present in unistd.h. But they still can be implemented as an external
 13    library (e.g. gnu pth in pthread emulation) */
 14 # ifdef HAVE_PTHREAD_H
 15 #  include <pthread.h> /* _POSIX_THREADS */
 16 # endif
 17 #endif
 18 
 19 #ifndef DONT_HAVE_STDIO_H
 20 #include <stdio.h>
 21 #endif
 22 
 23 #include <stdlib.h>
 24 
 25 #ifdef __sgi
 26 #ifndef HAVE_PTHREAD_H /* XXX Need to check in configure.in */
 27 #undef _POSIX_THREADS
 28 #endif
 29 #endif
 30 
 31 #include "pythread.h"
 32 
 33 #ifndef _POSIX_THREADS
 34 
 35 #ifdef __sgi
 36 #define SGI_THREADS
 37 #endif
 38 
 39 #ifdef HAVE_THREAD_H
 40 #define SOLARIS_THREADS
 41 #endif
 42 
 43 #if defined(sun) && !defined(SOLARIS_THREADS)
 44 #define SUN_LWP
 45 #endif
 46 
 47 /* Check if we're running on HP-UX and _SC_THREADS is defined. If so, then
 48    enough of the Posix threads package is implemented to support python
 49    threads.
 50 
 51    This is valid for HP-UX 11.23 running on an ia64 system. If needed, add
 52    a check of __ia64 to verify that we're running on a ia64 system instead
 53    of a pa-risc system.
 54 */
 55 #ifdef __hpux
 56 #ifdef _SC_THREADS
 57 #define _POSIX_THREADS
 58 #endif
 59 #endif
 60 
 61 #endif /* _POSIX_THREADS */
 62 
 63 
 64 #ifdef Py_DEBUG
 65 static int thread_debug = 0;
 66 #define dprintf(args)   (void)((thread_debug & 1) && printf args)
 67 #define d2printf(args)  ((thread_debug & 8) && printf args)
 68 #else
 69 #define dprintf(args)
 70 #define d2printf(args)
 71 #endif
 72 
 73 static int initialized;
 74 
 75 static void PyThread__init_thread(void); /* Forward */
 76 
 77 void
 78 PyThread_init_thread(void)
 79 {
 80 #ifdef Py_DEBUG
 81     char *p = Py_GETENV("PYTHONTHREADDEBUG");
 82 
 83     if (p) {
 84         if (*p)
 85             thread_debug = atoi(p);
 86         else
 87             thread_debug = 1;
 88     }
 89 #endif /* Py_DEBUG */
 90     if (initialized)
 91         return;
 92     initialized = 1;
 93     dprintf(("PyThread_init_thread called\n"));
 94     PyThread__init_thread();
 95 }
 96 
 97 /* Support for runtime thread stack size tuning.
 98    A value of 0 means using the platform's default stack size
 99    or the size specified by the THREAD_STACK_SIZE macro. */
100 static size_t _pythread_stacksize = 0;
101 
102 #ifdef SGI_THREADS
103 #include "thread_sgi.h"
104 #endif
105 
106 #ifdef SOLARIS_THREADS
107 #include "thread_solaris.h"
108 #endif
109 
110 #ifdef SUN_LWP
111 #include "thread_lwp.h"
112 #endif
113 
114 #ifdef HAVE_PTH
115 #include "thread_pth.h"
116 #undef _POSIX_THREADS
117 #endif
118 
119 #ifdef _POSIX_THREADS
120 #include "thread_pthread.h"
121 #endif
122 
123 #ifdef C_THREADS
124 #include "thread_cthread.h"
125 #endif
126 
127 #ifdef NT_THREADS
128 #include "thread_nt.h"
129 #endif
130 
131 #ifdef OS2_THREADS
132 #include "thread_os2.h"
133 #endif
134 
135 #ifdef BEOS_THREADS
136 #include "thread_beos.h"
137 #endif
138 
139 #ifdef PLAN9_THREADS
140 #include "thread_plan9.h"
141 #endif
142 
143 #ifdef ATHEOS_THREADS
144 #include "thread_atheos.h"
145 #endif
146 
147 /*
148 #ifdef FOOBAR_THREADS
149 #include "thread_foobar.h"
150 #endif
151 */
152 
153 /* return the current thread stack size */
154 size_t
155 PyThread_get_stacksize(void)
156 {
157     return _pythread_stacksize;
158 }
159 
160 /* Only platforms defining a THREAD_SET_STACKSIZE() macro
161    in thread_<platform>.h support changing the stack size.
162    Return 0 if stack size is valid,
163       -1 if stack size value is invalid,
164       -2 if setting stack size is not supported. */
165 int
166 PyThread_set_stacksize(size_t size)
167 {
168 #if defined(THREAD_SET_STACKSIZE)
169     return THREAD_SET_STACKSIZE(size);
170 #else
171     return -2;
172 #endif
173 }
174 
175 #ifndef Py_HAVE_NATIVE_TLS
176 /* If the platform has not supplied a platform specific
177    TLS implementation, provide our own.
178 
179    This code stolen from "thread_sgi.h", where it was the only
180    implementation of an existing Python TLS API.
181 */
182 /* ------------------------------------------------------------------------
183 Per-thread data ("key") support.
184 
185 Use PyThread_create_key() to create a new key.  This is typically shared
186 across threads.
187 
188 Use PyThread_set_key_value(thekey, value) to associate void* value with
189 thekey in the current thread.  Each thread has a distinct mapping of thekey
190 to a void* value.  Caution:  if the current thread already has a mapping
191 for thekey, value is ignored.
192 
193 Use PyThread_get_key_value(thekey) to retrieve the void* value associated
194 with thekey in the current thread.  This returns NULL if no value is
195 associated with thekey in the current thread.
196 
197 Use PyThread_delete_key_value(thekey) to forget the current thread's associated
198 value for thekey.  PyThread_delete_key(thekey) forgets the values associated
199 with thekey across *all* threads.
200 
201 While some of these functions have error-return values, none set any
202 Python exception.
203 
204 None of the functions does memory management on behalf of the void* values.
205 You need to allocate and deallocate them yourself.  If the void* values
206 happen to be PyObject*, these functions don't do refcount operations on
207 them either.
208 
209 The GIL does not need to be held when calling these functions; they supply
210 their own locking.  This isn't true of PyThread_create_key(), though (see
211 next paragraph).
212 
213 There's a hidden assumption that PyThread_create_key() will be called before
214 any of the other functions are called.  There's also a hidden assumption
215 that calls to PyThread_create_key() are serialized externally.
216 ------------------------------------------------------------------------ */
217 
218 /* A singly-linked list of struct key objects remembers all the key->value
219  * associations.  File static keyhead heads the list.  keymutex is used
220  * to enforce exclusion internally.
221  */
222 struct key {
223     /* Next record in the list, or NULL if this is the last record. */
224     struct key *next;
225 
226     /* The thread id, according to PyThread_get_thread_ident(). */
227     long id;
228 
229     /* The key and its associated value. */
230     int key;
231     void *value;
232 };
233 
234 static struct key *keyhead = NULL;
235 static PyThread_type_lock keymutex = NULL;
236 static int nkeys = 0;  /* PyThread_create_key() hands out nkeys+1 next */
237 
238 /* Internal helper.
239  * If the current thread has a mapping for key, the appropriate struct key*
240  * is returned.  NB:  value is ignored in this case!
241  * If there is no mapping for key in the current thread, then:
242  *     If value is NULL, NULL is returned.
243  *     Else a mapping of key to value is created for the current thread,
244  *     and a pointer to a new struct key* is returned; except that if
245  *     malloc() can't find room for a new struct key*, NULL is returned.
246  * So when value==NULL, this acts like a pure lookup routine, and when
247  * value!=NULL, this acts like dict.setdefault(), returning an existing
248  * mapping if one exists, else creating a new mapping.
249  *
250  * Caution:  this used to be too clever, trying to hold keymutex only
251  * around the "p->next = keyhead; keyhead = p" pair.  That allowed
252  * another thread to mutate the list, via key deletion, concurrent with
253  * find_key() crawling over the list.  Hilarity ensued.  For example, when
254  * the for-loop here does "p = p->next", p could end up pointing at a
255  * record that PyThread_delete_key_value() was concurrently free()'ing.
256  * That could lead to anything, from failing to find a key that exists, to
257  * segfaults.  Now we lock the whole routine.
258  */
259 static struct key *
260 find_key(int key, void *value)
261 {
262     struct key *p, *prev_p;
263     long id = PyThread_get_thread_ident();
264 
265     if (!keymutex)
266         return NULL;
267     PyThread_acquire_lock(keymutex, 1);
268     prev_p = NULL;
269     for (p = keyhead; p != NULL; p = p->next) {
270         if (p->id == id && p->key == key)
271             goto Done;
272         /* Sanity check.  These states should never happen but if
273          * they do we must abort.  Otherwise we'll end up spinning in
274          * in a tight loop with the lock held.  A similar check is done
275          * in pystate.c tstate_delete_common().  */
276         if (p == prev_p)
277             Py_FatalError("tls find_key: small circular list(!)");
278         prev_p = p;
279         if (p->next == keyhead)
280             Py_FatalError("tls find_key: circular list(!)");
281     }
282     if (value == NULL) {
283         assert(p == NULL);
284         goto Done;
285     }
286     p = (struct key *)malloc(sizeof(struct key));
287     if (p != NULL) {
288         p->id = id;
289         p->key = key;
290         p->value = value;
291         p->next = keyhead;
292         keyhead = p;
293     }
294  Done:
295     PyThread_release_lock(keymutex);
296     return p;
297 }
298 
299 /* Return a new key.  This must be called before any other functions in
300  * this family, and callers must arrange to serialize calls to this
301  * function.  No violations are detected.
302  */
303 int
304 PyThread_create_key(void)
305 {
306     /* All parts of this function are wrong if it's called by multiple
307      * threads simultaneously.
308      */
309     if (keymutex == NULL)
310         keymutex = PyThread_allocate_lock();
311     return ++nkeys;
312 }
313 
314 /* Forget the associations for key across *all* threads. */
315 void
316 PyThread_delete_key(int key)
317 {
318     struct key *p, **q;
319 
320     PyThread_acquire_lock(keymutex, 1);
321     q = &keyhead;
322     while ((p = *q) != NULL) {
323         if (p->key == key) {
324             *q = p->next;
325             free((void *)p);
326             /* NB This does *not* free p->value! */
327         }
328         else
329             q = &p->next;
330     }
331     PyThread_release_lock(keymutex);
332 }
333 
334 /* Confusing:  If the current thread has an association for key,
335  * value is ignored, and 0 is returned.  Else an attempt is made to create
336  * an association of key to value for the current thread.  0 is returned
337  * if that succeeds, but -1 is returned if there's not enough memory
338  * to create the association.  value must not be NULL.
339  */
340 int
341 PyThread_set_key_value(int key, void *value)
342 {
343     struct key *p;
344 
345     assert(value != NULL);
346     p = find_key(key, value);
347     if (p == NULL)
348         return -1;
349     else
350         return 0;
351 }
352 
353 /* Retrieve the value associated with key in the current thread, or NULL
354  * if the current thread doesn't have an association for key.
355  */
356 void *
357 PyThread_get_key_value(int key)
358 {
359     struct key *p = find_key(key, NULL);
360 
361     if (p == NULL)
362         return NULL;
363     else
364         return p->value;
365 }
366 
367 /* Forget the current thread's association for key, if any. */
368 void
369 PyThread_delete_key_value(int key)
370 {
371     long id = PyThread_get_thread_ident();
372     struct key *p, **q;
373 
374     PyThread_acquire_lock(keymutex, 1);
375     q = &keyhead;
376     while ((p = *q) != NULL) {
377         if (p->key == key && p->id == id) {
378             *q = p->next;
379             free((void *)p);
380             /* NB This does *not* free p->value! */
381             break;
382         }
383         else
384             q = &p->next;
385     }
386     PyThread_release_lock(keymutex);
387 }
388 
389 /* Forget everything not associated with the current thread id.
390  * This function is called from PyOS_AfterFork().  It is necessary
391  * because other thread ids which were in use at the time of the fork
392  * may be reused for new threads created in the forked process.
393  */
394 void
395 PyThread_ReInitTLS(void)
396 {
397     long id = PyThread_get_thread_ident();
398     struct key *p, **q;
399 
400     if (!keymutex)
401         return;
402 
403     /* As with interpreter_lock in PyEval_ReInitThreads()
404        we just create a new lock without freeing the old one */
405     keymutex = PyThread_allocate_lock();
406 
407     /* Delete all keys which do not match the current thread id */
408     q = &keyhead;
409     while ((p = *q) != NULL) {
410         if (p->id != id) {
411             *q = p->next;
412             free((void *)p);
413             /* NB This does *not* free p->value! */
414         }
415         else
416             q = &p->next;
417     }
418 }
419 
420 #endif /* Py_HAVE_NATIVE_TLS */