/Python/thread.c

http://unladen-swallow.googlecode.com/ · C · 425 lines · 236 code · 57 blank · 132 comment · 44 complexity · ca37af5573e6a0920f09524301a80ac2 MD5 · raw file

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