Line data Source code
1 :
2 : /* Thread and interpreter state structures and their interfaces */
3 :
4 : #include "Python.h"
5 :
6 : /* --------------------------------------------------------------------------
7 : CAUTION
8 :
9 : Always use malloc() and free() directly in this file. A number of these
10 : functions are advertised as safe to call when the GIL isn't held, and in
11 : a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's debugging
12 : obmalloc functions. Those aren't thread-safe (they rely on the GIL to avoid
13 : the expense of doing their own locking).
14 : -------------------------------------------------------------------------- */
15 :
16 : #ifdef HAVE_DLOPEN
17 : #ifdef HAVE_DLFCN_H
18 : #include <dlfcn.h>
19 : #endif
20 : #ifndef RTLD_LAZY
21 : #define RTLD_LAZY 1
22 : #endif
23 : #endif
24 :
25 : #ifdef __cplusplus
26 : extern "C" {
27 : #endif
28 :
29 : #ifdef WITH_THREAD
30 : #include "pythread.h"
31 : static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
32 : #define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
33 : #define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
34 : #define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
35 :
36 : /* The single PyInterpreterState used by this process'
37 : GILState implementation
38 : */
39 : static PyInterpreterState *autoInterpreterState = NULL;
40 : static int autoTLSkey = 0;
41 : #else
42 : #define HEAD_INIT() /* Nothing */
43 : #define HEAD_LOCK() /* Nothing */
44 : #define HEAD_UNLOCK() /* Nothing */
45 : #endif
46 :
47 : static PyInterpreterState *interp_head = NULL;
48 :
49 : /* Assuming the current thread holds the GIL, this is the
50 : PyThreadState for the current thread. */
51 : _Py_atomic_address _PyThreadState_Current = {NULL};
52 : PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
53 :
54 : #ifdef WITH_THREAD
55 : static void _PyGILState_NoteThreadState(PyThreadState* tstate);
56 : #endif
57 :
58 :
59 : PyInterpreterState *
60 1 : PyInterpreterState_New(void)
61 : {
62 1 : PyInterpreterState *interp = (PyInterpreterState *)
63 : malloc(sizeof(PyInterpreterState));
64 :
65 1 : if (interp != NULL) {
66 1 : HEAD_INIT();
67 : #ifdef WITH_THREAD
68 1 : if (head_mutex == NULL)
69 0 : Py_FatalError("Can't initialize threads for interpreter");
70 : #endif
71 1 : interp->modules = NULL;
72 1 : interp->modules_by_index = NULL;
73 1 : interp->sysdict = NULL;
74 1 : interp->builtins = NULL;
75 1 : interp->tstate_head = NULL;
76 1 : interp->codec_search_path = NULL;
77 1 : interp->codec_search_cache = NULL;
78 1 : interp->codec_error_registry = NULL;
79 1 : interp->codecs_initialized = 0;
80 1 : interp->fscodec_initialized = 0;
81 1 : interp->importlib = NULL;
82 : #ifdef HAVE_DLOPEN
83 : #ifdef RTLD_NOW
84 1 : interp->dlopenflags = RTLD_NOW;
85 : #else
86 : interp->dlopenflags = RTLD_LAZY;
87 : #endif
88 : #endif
89 : #ifdef WITH_TSC
90 : interp->tscdump = 0;
91 : #endif
92 :
93 1 : HEAD_LOCK();
94 1 : interp->next = interp_head;
95 1 : interp_head = interp;
96 1 : HEAD_UNLOCK();
97 : }
98 :
99 1 : return interp;
100 : }
101 :
102 :
103 : void
104 0 : PyInterpreterState_Clear(PyInterpreterState *interp)
105 : {
106 : PyThreadState *p;
107 0 : HEAD_LOCK();
108 0 : for (p = interp->tstate_head; p != NULL; p = p->next)
109 0 : PyThreadState_Clear(p);
110 0 : HEAD_UNLOCK();
111 0 : Py_CLEAR(interp->codec_search_path);
112 0 : Py_CLEAR(interp->codec_search_cache);
113 0 : Py_CLEAR(interp->codec_error_registry);
114 0 : Py_CLEAR(interp->modules);
115 0 : Py_CLEAR(interp->modules_by_index);
116 0 : Py_CLEAR(interp->sysdict);
117 0 : Py_CLEAR(interp->builtins);
118 0 : Py_CLEAR(interp->importlib);
119 0 : }
120 :
121 :
122 : static void
123 0 : zapthreads(PyInterpreterState *interp)
124 : {
125 : PyThreadState *p;
126 : /* No need to lock the mutex here because this should only happen
127 : when the threads are all really dead (XXX famous last words). */
128 0 : while ((p = interp->tstate_head) != NULL) {
129 0 : PyThreadState_Delete(p);
130 : }
131 0 : }
132 :
133 :
134 : void
135 0 : PyInterpreterState_Delete(PyInterpreterState *interp)
136 : {
137 : PyInterpreterState **p;
138 0 : zapthreads(interp);
139 0 : HEAD_LOCK();
140 0 : for (p = &interp_head; ; p = &(*p)->next) {
141 0 : if (*p == NULL)
142 0 : Py_FatalError(
143 : "PyInterpreterState_Delete: invalid interp");
144 0 : if (*p == interp)
145 0 : break;
146 0 : }
147 0 : if (interp->tstate_head != NULL)
148 0 : Py_FatalError("PyInterpreterState_Delete: remaining threads");
149 0 : *p = interp->next;
150 0 : HEAD_UNLOCK();
151 0 : free(interp);
152 : #ifdef WITH_THREAD
153 0 : if (interp_head == NULL && head_mutex != NULL) {
154 0 : PyThread_free_lock(head_mutex);
155 0 : head_mutex = NULL;
156 : }
157 : #endif
158 0 : }
159 :
160 :
161 : /* Default implementation for _PyThreadState_GetFrame */
162 : static struct _frame *
163 94 : threadstate_getframe(PyThreadState *self)
164 : {
165 94 : return self->frame;
166 : }
167 :
168 : static PyThreadState *
169 46 : new_threadstate(PyInterpreterState *interp, int init)
170 : {
171 46 : PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState));
172 :
173 46 : if (_PyThreadState_GetFrame == NULL)
174 1 : _PyThreadState_GetFrame = threadstate_getframe;
175 :
176 46 : if (tstate != NULL) {
177 46 : tstate->interp = interp;
178 :
179 46 : tstate->frame = NULL;
180 46 : tstate->recursion_depth = 0;
181 46 : tstate->overflowed = 0;
182 46 : tstate->recursion_critical = 0;
183 46 : tstate->tracing = 0;
184 46 : tstate->use_tracing = 0;
185 46 : tstate->tick_counter = 0;
186 46 : tstate->gilstate_counter = 0;
187 46 : tstate->async_exc = NULL;
188 : #ifdef WITH_THREAD
189 46 : tstate->thread_id = PyThread_get_thread_ident();
190 : #else
191 : tstate->thread_id = 0;
192 : #endif
193 :
194 46 : tstate->dict = NULL;
195 :
196 46 : tstate->curexc_type = NULL;
197 46 : tstate->curexc_value = NULL;
198 46 : tstate->curexc_traceback = NULL;
199 :
200 46 : tstate->exc_type = NULL;
201 46 : tstate->exc_value = NULL;
202 46 : tstate->exc_traceback = NULL;
203 :
204 46 : tstate->c_profilefunc = NULL;
205 46 : tstate->c_tracefunc = NULL;
206 46 : tstate->c_profileobj = NULL;
207 46 : tstate->c_traceobj = NULL;
208 :
209 46 : tstate->trash_delete_nesting = 0;
210 46 : tstate->trash_delete_later = NULL;
211 :
212 46 : if (init)
213 46 : _PyThreadState_Init(tstate);
214 :
215 46 : HEAD_LOCK();
216 46 : tstate->next = interp->tstate_head;
217 46 : interp->tstate_head = tstate;
218 46 : HEAD_UNLOCK();
219 : }
220 :
221 46 : return tstate;
222 : }
223 :
224 : PyThreadState *
225 46 : PyThreadState_New(PyInterpreterState *interp)
226 : {
227 46 : return new_threadstate(interp, 1);
228 : }
229 :
230 : PyThreadState *
231 0 : _PyThreadState_Prealloc(PyInterpreterState *interp)
232 : {
233 0 : return new_threadstate(interp, 0);
234 : }
235 :
236 : void
237 46 : _PyThreadState_Init(PyThreadState *tstate)
238 : {
239 : #ifdef WITH_THREAD
240 46 : _PyGILState_NoteThreadState(tstate);
241 : #endif
242 46 : }
243 :
244 : PyObject*
245 4 : PyState_FindModule(struct PyModuleDef* module)
246 : {
247 4 : Py_ssize_t index = module->m_base.m_index;
248 4 : PyInterpreterState *state = PyThreadState_GET()->interp;
249 : PyObject *res;
250 4 : if (index == 0)
251 0 : return NULL;
252 4 : if (state->modules_by_index == NULL)
253 0 : return NULL;
254 4 : if (index >= PyList_GET_SIZE(state->modules_by_index))
255 0 : return NULL;
256 4 : res = PyList_GET_ITEM(state->modules_by_index, index);
257 4 : return res==Py_None ? NULL : res;
258 : }
259 :
260 : int
261 23 : _PyState_AddModule(PyObject* module, struct PyModuleDef* def)
262 : {
263 23 : PyInterpreterState *state = PyThreadState_GET()->interp;
264 23 : if (!def)
265 0 : return -1;
266 23 : if (!state->modules_by_index) {
267 1 : state->modules_by_index = PyList_New(0);
268 1 : if (!state->modules_by_index)
269 0 : return -1;
270 : }
271 71 : while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
272 25 : if (PyList_Append(state->modules_by_index, Py_None) < 0)
273 0 : return -1;
274 23 : Py_INCREF(module);
275 23 : return PyList_SetItem(state->modules_by_index,
276 : def->m_base.m_index, module);
277 : }
278 :
279 : int
280 0 : PyState_AddModule(PyObject* module, struct PyModuleDef* def)
281 : {
282 : Py_ssize_t index;
283 0 : PyInterpreterState *state = PyThreadState_GET()->interp;
284 0 : if (!def) {
285 0 : Py_FatalError("PyState_AddModule: Module Definition is NULL");
286 0 : return -1;
287 : }
288 0 : index = def->m_base.m_index;
289 0 : if (state->modules_by_index) {
290 0 : if(PyList_GET_SIZE(state->modules_by_index) >= index) {
291 0 : if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
292 0 : Py_FatalError("PyState_AddModule: Module already added!");
293 0 : return -1;
294 : }
295 : }
296 : }
297 0 : return _PyState_AddModule(module, def);
298 : }
299 :
300 : int
301 0 : PyState_RemoveModule(struct PyModuleDef* def)
302 : {
303 0 : Py_ssize_t index = def->m_base.m_index;
304 0 : PyInterpreterState *state = PyThreadState_GET()->interp;
305 0 : if (index == 0) {
306 0 : Py_FatalError("PyState_RemoveModule: Module index invalid.");
307 0 : return -1;
308 : }
309 0 : if (state->modules_by_index == NULL) {
310 0 : Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
311 0 : return -1;
312 : }
313 0 : if (index > PyList_GET_SIZE(state->modules_by_index)) {
314 0 : Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
315 0 : return -1;
316 : }
317 0 : return PyList_SetItem(state->modules_by_index, index, Py_None);
318 : }
319 :
320 : void
321 45 : PyThreadState_Clear(PyThreadState *tstate)
322 : {
323 45 : if (Py_VerboseFlag && tstate->frame != NULL)
324 0 : fprintf(stderr,
325 : "PyThreadState_Clear: warning: thread still has a frame\n");
326 :
327 45 : Py_CLEAR(tstate->frame);
328 :
329 45 : Py_CLEAR(tstate->dict);
330 45 : Py_CLEAR(tstate->async_exc);
331 :
332 45 : Py_CLEAR(tstate->curexc_type);
333 45 : Py_CLEAR(tstate->curexc_value);
334 45 : Py_CLEAR(tstate->curexc_traceback);
335 :
336 45 : Py_CLEAR(tstate->exc_type);
337 45 : Py_CLEAR(tstate->exc_value);
338 45 : Py_CLEAR(tstate->exc_traceback);
339 :
340 45 : tstate->c_profilefunc = NULL;
341 45 : tstate->c_tracefunc = NULL;
342 45 : Py_CLEAR(tstate->c_profileobj);
343 45 : Py_CLEAR(tstate->c_traceobj);
344 45 : }
345 :
346 :
347 : /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
348 : static void
349 45 : tstate_delete_common(PyThreadState *tstate)
350 : {
351 : PyInterpreterState *interp;
352 : PyThreadState **p;
353 45 : PyThreadState *prev_p = NULL;
354 45 : if (tstate == NULL)
355 0 : Py_FatalError("PyThreadState_Delete: NULL tstate");
356 45 : interp = tstate->interp;
357 45 : if (interp == NULL)
358 0 : Py_FatalError("PyThreadState_Delete: NULL interp");
359 45 : HEAD_LOCK();
360 47 : for (p = &interp->tstate_head; ; p = &(*p)->next) {
361 47 : if (*p == NULL)
362 0 : Py_FatalError(
363 : "PyThreadState_Delete: invalid tstate");
364 47 : if (*p == tstate)
365 45 : break;
366 : /* Sanity check. These states should never happen but if
367 : * they do we must abort. Otherwise we'll end up spinning in
368 : * in a tight loop with the lock held. A similar check is done
369 : * in thread.c find_key(). */
370 2 : if (*p == prev_p)
371 0 : Py_FatalError(
372 : "PyThreadState_Delete: small circular list(!)"
373 : " and tstate not found.");
374 2 : prev_p = *p;
375 2 : if ((*p)->next == interp->tstate_head)
376 0 : Py_FatalError(
377 : "PyThreadState_Delete: circular list(!) and"
378 : " tstate not found.");
379 2 : }
380 45 : *p = tstate->next;
381 45 : HEAD_UNLOCK();
382 45 : free(tstate);
383 45 : }
384 :
385 :
386 : void
387 45 : PyThreadState_Delete(PyThreadState *tstate)
388 : {
389 45 : if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current))
390 0 : Py_FatalError("PyThreadState_Delete: tstate is still current");
391 45 : tstate_delete_common(tstate);
392 : #ifdef WITH_THREAD
393 45 : if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
394 34 : PyThread_delete_key_value(autoTLSkey);
395 : #endif /* WITH_THREAD */
396 45 : }
397 :
398 :
399 : #ifdef WITH_THREAD
400 : void
401 0 : PyThreadState_DeleteCurrent()
402 : {
403 0 : PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
404 : &_PyThreadState_Current);
405 0 : if (tstate == NULL)
406 0 : Py_FatalError(
407 : "PyThreadState_DeleteCurrent: no current tstate");
408 0 : _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL);
409 0 : tstate_delete_common(tstate);
410 0 : if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
411 0 : PyThread_delete_key_value(autoTLSkey);
412 0 : PyEval_ReleaseLock();
413 0 : }
414 : #endif /* WITH_THREAD */
415 :
416 :
417 : PyThreadState *
418 1894 : PyThreadState_Get(void)
419 : {
420 1894 : PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
421 : &_PyThreadState_Current);
422 1894 : if (tstate == NULL)
423 0 : Py_FatalError("PyThreadState_Get: no current thread");
424 :
425 1894 : return tstate;
426 : }
427 :
428 :
429 : PyThreadState *
430 4664 : PyThreadState_Swap(PyThreadState *newts)
431 : {
432 4664 : PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed(
433 : &_PyThreadState_Current);
434 :
435 4664 : _Py_atomic_store_relaxed(&_PyThreadState_Current, newts);
436 : /* It should not be possible for more than one thread state
437 : to be used for a thread. Check this the best we can in debug
438 : builds.
439 : */
440 : #if defined(Py_DEBUG) && defined(WITH_THREAD)
441 : if (newts) {
442 : /* This can be called from PyEval_RestoreThread(). Similar
443 : to it, we need to ensure errno doesn't change.
444 : */
445 : int err = errno;
446 : PyThreadState *check = PyGILState_GetThisThreadState();
447 : if (check && check->interp == newts->interp && check != newts)
448 : Py_FatalError("Invalid thread state for this thread");
449 : errno = err;
450 : }
451 : #endif
452 4664 : return oldts;
453 : }
454 :
455 : /* An extension mechanism to store arbitrary additional per-thread state.
456 : PyThreadState_GetDict() returns a dictionary that can be used to hold such
457 : state; the caller should pick a unique key and store its state there. If
458 : PyThreadState_GetDict() returns NULL, an exception has *not* been raised
459 : and the caller should assume no per-thread state is available. */
460 :
461 : PyObject *
462 874 : PyThreadState_GetDict(void)
463 : {
464 874 : PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
465 : &_PyThreadState_Current);
466 874 : if (tstate == NULL)
467 0 : return NULL;
468 :
469 874 : if (tstate->dict == NULL) {
470 : PyObject *d;
471 46 : tstate->dict = d = PyDict_New();
472 46 : if (d == NULL)
473 0 : PyErr_Clear();
474 : }
475 874 : return tstate->dict;
476 : }
477 :
478 :
479 : /* Asynchronously raise an exception in a thread.
480 : Requested by Just van Rossum and Alex Martelli.
481 : To prevent naive misuse, you must write your own extension
482 : to call this, or use ctypes. Must be called with the GIL held.
483 : Returns the number of tstates modified (normally 1, but 0 if `id` didn't
484 : match any known thread id). Can be called with exc=NULL to clear an
485 : existing async exception. This raises no exceptions. */
486 :
487 : int
488 0 : PyThreadState_SetAsyncExc(long id, PyObject *exc) {
489 0 : PyThreadState *tstate = PyThreadState_GET();
490 0 : PyInterpreterState *interp = tstate->interp;
491 : PyThreadState *p;
492 :
493 : /* Although the GIL is held, a few C API functions can be called
494 : * without the GIL held, and in particular some that create and
495 : * destroy thread and interpreter states. Those can mutate the
496 : * list of thread states we're traversing, so to prevent that we lock
497 : * head_mutex for the duration.
498 : */
499 0 : HEAD_LOCK();
500 0 : for (p = interp->tstate_head; p != NULL; p = p->next) {
501 0 : if (p->thread_id == id) {
502 : /* Tricky: we need to decref the current value
503 : * (if any) in p->async_exc, but that can in turn
504 : * allow arbitrary Python code to run, including
505 : * perhaps calls to this function. To prevent
506 : * deadlock, we need to release head_mutex before
507 : * the decref.
508 : */
509 0 : PyObject *old_exc = p->async_exc;
510 0 : Py_XINCREF(exc);
511 0 : p->async_exc = exc;
512 0 : HEAD_UNLOCK();
513 0 : Py_XDECREF(old_exc);
514 0 : _PyEval_SignalAsyncExc();
515 0 : return 1;
516 : }
517 : }
518 0 : HEAD_UNLOCK();
519 0 : return 0;
520 : }
521 :
522 :
523 : /* Routines for advanced debuggers, requested by David Beazley.
524 : Don't use unless you know what you are doing! */
525 :
526 : PyInterpreterState *
527 1 : PyInterpreterState_Head(void)
528 : {
529 1 : return interp_head;
530 : }
531 :
532 : PyInterpreterState *
533 0 : PyInterpreterState_Next(PyInterpreterState *interp) {
534 0 : return interp->next;
535 : }
536 :
537 : PyThreadState *
538 0 : PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
539 0 : return interp->tstate_head;
540 : }
541 :
542 : PyThreadState *
543 0 : PyThreadState_Next(PyThreadState *tstate) {
544 0 : return tstate->next;
545 : }
546 :
547 : /* The implementation of sys._current_frames(). This is intended to be
548 : called with the GIL held, as it will be when called via
549 : sys._current_frames(). It's possible it would work fine even without
550 : the GIL held, but haven't thought enough about that.
551 : */
552 : PyObject *
553 0 : _PyThread_CurrentFrames(void)
554 : {
555 : PyObject *result;
556 : PyInterpreterState *i;
557 :
558 0 : result = PyDict_New();
559 0 : if (result == NULL)
560 0 : return NULL;
561 :
562 : /* for i in all interpreters:
563 : * for t in all of i's thread states:
564 : * if t's frame isn't NULL, map t's id to its frame
565 : * Because these lists can mutate even when the GIL is held, we
566 : * need to grab head_mutex for the duration.
567 : */
568 0 : HEAD_LOCK();
569 0 : for (i = interp_head; i != NULL; i = i->next) {
570 : PyThreadState *t;
571 0 : for (t = i->tstate_head; t != NULL; t = t->next) {
572 : PyObject *id;
573 : int stat;
574 0 : struct _frame *frame = t->frame;
575 0 : if (frame == NULL)
576 0 : continue;
577 0 : id = PyLong_FromLong(t->thread_id);
578 0 : if (id == NULL)
579 0 : goto Fail;
580 0 : stat = PyDict_SetItem(result, id, (PyObject *)frame);
581 0 : Py_DECREF(id);
582 0 : if (stat < 0)
583 0 : goto Fail;
584 : }
585 : }
586 0 : HEAD_UNLOCK();
587 0 : return result;
588 :
589 : Fail:
590 0 : HEAD_UNLOCK();
591 0 : Py_DECREF(result);
592 0 : return NULL;
593 : }
594 :
595 : /* Python "auto thread state" API. */
596 : #ifdef WITH_THREAD
597 :
598 : /* Keep this as a static, as it is not reliable! It can only
599 : ever be compared to the state for the *current* thread.
600 : * If not equal, then it doesn't matter that the actual
601 : value may change immediately after comparison, as it can't
602 : possibly change to the current thread's state.
603 : * If equal, then the current thread holds the lock, so the value can't
604 : change until we yield the lock.
605 : */
606 : static int
607 0 : PyThreadState_IsCurrent(PyThreadState *tstate)
608 : {
609 : /* Must be the tstate for this thread */
610 : assert(PyGILState_GetThisThreadState()==tstate);
611 0 : return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current);
612 : }
613 :
614 : /* Internal initialization/finalization functions called by
615 : Py_Initialize/Py_Finalize
616 : */
617 : void
618 1 : _PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
619 : {
620 : assert(i && t); /* must init with valid states */
621 1 : autoTLSkey = PyThread_create_key();
622 1 : if (autoTLSkey == -1)
623 0 : Py_FatalError("Could not allocate TLS entry");
624 1 : autoInterpreterState = i;
625 : assert(PyThread_get_key_value(autoTLSkey) == NULL);
626 : assert(t->gilstate_counter == 0);
627 :
628 1 : _PyGILState_NoteThreadState(t);
629 1 : }
630 :
631 : void
632 0 : _PyGILState_Fini(void)
633 : {
634 0 : PyThread_delete_key(autoTLSkey);
635 0 : autoInterpreterState = NULL;
636 0 : }
637 :
638 : /* Reset the TLS key - called by PyOS_AfterFork().
639 : * This should not be necessary, but some - buggy - pthread implementations
640 : * don't reset TLS upon fork(), see issue #10517.
641 : */
642 : void
643 0 : _PyGILState_Reinit(void)
644 : {
645 0 : PyThreadState *tstate = PyGILState_GetThisThreadState();
646 0 : PyThread_delete_key(autoTLSkey);
647 0 : if ((autoTLSkey = PyThread_create_key()) == -1)
648 0 : Py_FatalError("Could not allocate TLS entry");
649 :
650 : /* If the thread had an associated auto thread state, reassociate it with
651 : * the new key. */
652 0 : if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
653 0 : Py_FatalError("Couldn't create autoTLSkey mapping");
654 0 : }
655 :
656 : /* When a thread state is created for a thread by some mechanism other than
657 : PyGILState_Ensure, it's important that the GILState machinery knows about
658 : it so it doesn't try to create another thread state for the thread (this is
659 : a better fix for SF bug #1010677 than the first one attempted).
660 : */
661 : static void
662 47 : _PyGILState_NoteThreadState(PyThreadState* tstate)
663 : {
664 : /* If autoTLSkey isn't initialized, this must be the very first
665 : threadstate created in Py_Initialize(). Don't do anything for now
666 : (we'll be back here when _PyGILState_Init is called). */
667 47 : if (!autoInterpreterState)
668 48 : return;
669 :
670 : /* Stick the thread state for this thread in thread local storage.
671 :
672 : The only situation where you can legitimately have more than one
673 : thread state for an OS level thread is when there are multiple
674 : interpreters, when:
675 :
676 : a) You shouldn't really be using the PyGILState_ APIs anyway,
677 : and:
678 :
679 : b) The slightly odd way PyThread_set_key_value works (see
680 : comments by its implementation) means that the first thread
681 : state created for that given OS level thread will "win",
682 : which seems reasonable behaviour.
683 : */
684 46 : if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
685 0 : Py_FatalError("Couldn't create autoTLSkey mapping");
686 :
687 : /* PyGILState_Release must not try to delete this thread state. */
688 46 : tstate->gilstate_counter = 1;
689 : }
690 :
691 : /* The public functions */
692 : PyThreadState *
693 0 : PyGILState_GetThisThreadState(void)
694 : {
695 0 : if (autoInterpreterState == NULL)
696 0 : return NULL;
697 0 : return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
698 : }
699 :
700 : PyGILState_STATE
701 0 : PyGILState_Ensure(void)
702 : {
703 : int current;
704 : PyThreadState *tcur;
705 : /* Note that we do not auto-init Python here - apart from
706 : potential races with 2 threads auto-initializing, pep-311
707 : spells out other issues. Embedders are expected to have
708 : called Py_Initialize() and usually PyEval_InitThreads().
709 : */
710 : assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
711 0 : tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
712 0 : if (tcur == NULL) {
713 : /* Create a new thread state for this thread */
714 0 : tcur = PyThreadState_New(autoInterpreterState);
715 0 : if (tcur == NULL)
716 0 : Py_FatalError("Couldn't create thread-state for new thread");
717 : /* This is our thread state! We'll need to delete it in the
718 : matching call to PyGILState_Release(). */
719 0 : tcur->gilstate_counter = 0;
720 0 : current = 0; /* new thread state is never current */
721 : }
722 : else
723 0 : current = PyThreadState_IsCurrent(tcur);
724 0 : if (current == 0)
725 0 : PyEval_RestoreThread(tcur);
726 : /* Update our counter in the thread-state - no need for locks:
727 : - tcur will remain valid as we hold the GIL.
728 : - the counter is safe as we are the only thread "allowed"
729 : to modify this value
730 : */
731 0 : ++tcur->gilstate_counter;
732 0 : return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
733 : }
734 :
735 : void
736 0 : PyGILState_Release(PyGILState_STATE oldstate)
737 : {
738 0 : PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
739 : autoTLSkey);
740 0 : if (tcur == NULL)
741 0 : Py_FatalError("auto-releasing thread-state, "
742 : "but no thread-state for this thread");
743 : /* We must hold the GIL and have our thread state current */
744 : /* XXX - remove the check - the assert should be fine,
745 : but while this is very new (April 2003), the extra check
746 : by release-only users can't hurt.
747 : */
748 0 : if (! PyThreadState_IsCurrent(tcur))
749 0 : Py_FatalError("This thread state must be current when releasing");
750 : assert(PyThreadState_IsCurrent(tcur));
751 0 : --tcur->gilstate_counter;
752 : assert(tcur->gilstate_counter >= 0); /* illegal counter value */
753 :
754 : /* If we're going to destroy this thread-state, we must
755 : * clear it while the GIL is held, as destructors may run.
756 : */
757 0 : if (tcur->gilstate_counter == 0) {
758 : /* can't have been locked when we created it */
759 : assert(oldstate == PyGILState_UNLOCKED);
760 0 : PyThreadState_Clear(tcur);
761 : /* Delete the thread-state. Note this releases the GIL too!
762 : * It's vital that the GIL be held here, to avoid shutdown
763 : * races; see bugs 225673 and 1061968 (that nasty bug has a
764 : * habit of coming back).
765 : */
766 0 : PyThreadState_DeleteCurrent();
767 : }
768 : /* Release the lock if necessary */
769 0 : else if (oldstate == PyGILState_UNLOCKED)
770 0 : PyEval_SaveThread();
771 0 : }
772 :
773 : #endif /* WITH_THREAD */
774 :
775 : #ifdef __cplusplus
776 : }
777 : #endif
778 :
779 :
|