2 /* Thread and interpreter state structures and their interfaces */
6 /* --------------------------------------------------------------------------
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 -------------------------------------------------------------------------- */
28 static PyThread_type_lock head_mutex
= NULL
; /* Protects interp->tstate_head */
29 #define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
30 #define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
31 #define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
37 /* The single PyInterpreterState used by this process'
38 GILState implementation
40 static PyInterpreterState
*autoInterpreterState
= NULL
;
41 static int autoTLSkey
= 0;
43 #define HEAD_INIT() /* Nothing */
44 #define HEAD_LOCK() /* Nothing */
45 #define HEAD_UNLOCK() /* Nothing */
48 static PyInterpreterState
*interp_head
= NULL
;
50 PyThreadState
*_PyThreadState_Current
= NULL
;
51 PyThreadFrameGetter _PyThreadState_GetFrame
= NULL
;
54 static void _PyGILState_NoteThreadState(PyThreadState
* tstate
);
59 PyInterpreterState_New(void)
61 PyInterpreterState
*interp
= (PyInterpreterState
*)
62 malloc(sizeof(PyInterpreterState
));
67 if (head_mutex
== NULL
)
68 Py_FatalError("Can't initialize threads for interpreter");
70 interp
->modules
= NULL
;
71 interp
->modules_reloading
= NULL
;
72 interp
->sysdict
= NULL
;
73 interp
->builtins
= NULL
;
74 interp
->tstate_head
= NULL
;
75 interp
->codec_search_path
= NULL
;
76 interp
->codec_search_cache
= NULL
;
77 interp
->codec_error_registry
= NULL
;
80 interp
->dlopenflags
= RTLD_NOW
;
82 interp
->dlopenflags
= RTLD_LAZY
;
90 interp
->next
= interp_head
;
100 PyInterpreterState_Clear(PyInterpreterState
*interp
)
104 for (p
= interp
->tstate_head
; p
!= NULL
; p
= p
->next
)
105 PyThreadState_Clear(p
);
107 Py_CLEAR(interp
->codec_search_path
);
108 Py_CLEAR(interp
->codec_search_cache
);
109 Py_CLEAR(interp
->codec_error_registry
);
110 Py_CLEAR(interp
->modules
);
111 Py_CLEAR(interp
->modules_reloading
);
112 Py_CLEAR(interp
->sysdict
);
113 Py_CLEAR(interp
->builtins
);
118 zapthreads(PyInterpreterState
*interp
)
121 /* No need to lock the mutex here because this should only happen
122 when the threads are all really dead (XXX famous last words). */
123 while ((p
= interp
->tstate_head
) != NULL
) {
124 PyThreadState_Delete(p
);
130 PyInterpreterState_Delete(PyInterpreterState
*interp
)
132 PyInterpreterState
**p
;
135 for (p
= &interp_head
; ; p
= &(*p
)->next
) {
138 "PyInterpreterState_Delete: invalid interp");
142 if (interp
->tstate_head
!= NULL
)
143 Py_FatalError("PyInterpreterState_Delete: remaining threads");
150 /* Default implementation for _PyThreadState_GetFrame */
151 static struct _frame
*
152 threadstate_getframe(PyThreadState
*self
)
157 static PyThreadState
*
158 new_threadstate(PyInterpreterState
*interp
, int init
)
160 PyThreadState
*tstate
= (PyThreadState
*)malloc(sizeof(PyThreadState
));
162 if (_PyThreadState_GetFrame
== NULL
)
163 _PyThreadState_GetFrame
= threadstate_getframe
;
165 if (tstate
!= NULL
) {
166 tstate
->interp
= interp
;
168 tstate
->frame
= NULL
;
169 tstate
->recursion_depth
= 0;
171 tstate
->use_tracing
= 0;
172 tstate
->tick_counter
= 0;
173 tstate
->gilstate_counter
= 0;
174 tstate
->async_exc
= NULL
;
176 tstate
->thread_id
= PyThread_get_thread_ident();
178 tstate
->thread_id
= 0;
183 tstate
->curexc_type
= NULL
;
184 tstate
->curexc_value
= NULL
;
185 tstate
->curexc_traceback
= NULL
;
187 tstate
->exc_type
= NULL
;
188 tstate
->exc_value
= NULL
;
189 tstate
->exc_traceback
= NULL
;
191 tstate
->c_profilefunc
= NULL
;
192 tstate
->c_tracefunc
= NULL
;
193 tstate
->c_profileobj
= NULL
;
194 tstate
->c_traceobj
= NULL
;
197 _PyThreadState_Init(tstate
);
200 tstate
->next
= interp
->tstate_head
;
201 interp
->tstate_head
= tstate
;
209 PyThreadState_New(PyInterpreterState
*interp
)
211 return new_threadstate(interp
, 1);
215 _PyThreadState_Prealloc(PyInterpreterState
*interp
)
217 return new_threadstate(interp
, 0);
221 _PyThreadState_Init(PyThreadState
*tstate
)
224 _PyGILState_NoteThreadState(tstate
);
229 PyThreadState_Clear(PyThreadState
*tstate
)
231 if (Py_VerboseFlag
&& tstate
->frame
!= NULL
)
233 "PyThreadState_Clear: warning: thread still has a frame\n");
235 Py_CLEAR(tstate
->frame
);
237 Py_CLEAR(tstate
->dict
);
238 Py_CLEAR(tstate
->async_exc
);
240 Py_CLEAR(tstate
->curexc_type
);
241 Py_CLEAR(tstate
->curexc_value
);
242 Py_CLEAR(tstate
->curexc_traceback
);
244 Py_CLEAR(tstate
->exc_type
);
245 Py_CLEAR(tstate
->exc_value
);
246 Py_CLEAR(tstate
->exc_traceback
);
248 tstate
->c_profilefunc
= NULL
;
249 tstate
->c_tracefunc
= NULL
;
250 Py_CLEAR(tstate
->c_profileobj
);
251 Py_CLEAR(tstate
->c_traceobj
);
255 /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
257 tstate_delete_common(PyThreadState
*tstate
)
259 PyInterpreterState
*interp
;
261 PyThreadState
*prev_p
= NULL
;
263 Py_FatalError("PyThreadState_Delete: NULL tstate");
264 interp
= tstate
->interp
;
266 Py_FatalError("PyThreadState_Delete: NULL interp");
268 for (p
= &interp
->tstate_head
; ; p
= &(*p
)->next
) {
271 "PyThreadState_Delete: invalid tstate");
274 /* Sanity check. These states should never happen but if
275 * they do we must abort. Otherwise we'll end up spinning in
276 * in a tight loop with the lock held. A similar check is done
277 * in thread.c find_key(). */
280 "PyThreadState_Delete: small circular list(!)"
281 " and tstate not found.");
283 if ((*p
)->next
== interp
->tstate_head
)
285 "PyThreadState_Delete: circular list(!) and"
286 " tstate not found.");
295 PyThreadState_Delete(PyThreadState
*tstate
)
297 if (tstate
== _PyThreadState_Current
)
298 Py_FatalError("PyThreadState_Delete: tstate is still current");
299 tstate_delete_common(tstate
);
301 if (autoTLSkey
&& PyThread_get_key_value(autoTLSkey
) == tstate
)
302 PyThread_delete_key_value(autoTLSkey
);
303 #endif /* WITH_THREAD */
309 PyThreadState_DeleteCurrent()
311 PyThreadState
*tstate
= _PyThreadState_Current
;
314 "PyThreadState_DeleteCurrent: no current tstate");
315 _PyThreadState_Current
= NULL
;
316 tstate_delete_common(tstate
);
317 if (autoTLSkey
&& PyThread_get_key_value(autoTLSkey
) == tstate
)
318 PyThread_delete_key_value(autoTLSkey
);
319 PyEval_ReleaseLock();
321 #endif /* WITH_THREAD */
325 PyThreadState_Get(void)
327 if (_PyThreadState_Current
== NULL
)
328 Py_FatalError("PyThreadState_Get: no current thread");
330 return _PyThreadState_Current
;
335 PyThreadState_Swap(PyThreadState
*newts
)
337 PyThreadState
*oldts
= _PyThreadState_Current
;
339 _PyThreadState_Current
= newts
;
340 /* It should not be possible for more than one thread state
341 to be used for a thread. Check this the best we can in debug
344 #if defined(Py_DEBUG) && defined(WITH_THREAD)
346 /* This can be called from PyEval_RestoreThread(). Similar
347 to it, we need to ensure errno doesn't change.
350 PyThreadState
*check
= PyGILState_GetThisThreadState();
351 if (check
&& check
->interp
== newts
->interp
&& check
!= newts
)
352 Py_FatalError("Invalid thread state for this thread");
359 /* An extension mechanism to store arbitrary additional per-thread state.
360 PyThreadState_GetDict() returns a dictionary that can be used to hold such
361 state; the caller should pick a unique key and store its state there. If
362 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
363 and the caller should assume no per-thread state is available. */
366 PyThreadState_GetDict(void)
368 if (_PyThreadState_Current
== NULL
)
371 if (_PyThreadState_Current
->dict
== NULL
) {
373 _PyThreadState_Current
->dict
= d
= PyDict_New();
377 return _PyThreadState_Current
->dict
;
381 /* Asynchronously raise an exception in a thread.
382 Requested by Just van Rossum and Alex Martelli.
383 To prevent naive misuse, you must write your own extension
384 to call this, or use ctypes. Must be called with the GIL held.
385 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
386 match any known thread id). Can be called with exc=NULL to clear an
387 existing async exception. This raises no exceptions. */
390 PyThreadState_SetAsyncExc(long id
, PyObject
*exc
) {
391 PyThreadState
*tstate
= PyThreadState_GET();
392 PyInterpreterState
*interp
= tstate
->interp
;
395 /* Although the GIL is held, a few C API functions can be called
396 * without the GIL held, and in particular some that create and
397 * destroy thread and interpreter states. Those can mutate the
398 * list of thread states we're traversing, so to prevent that we lock
399 * head_mutex for the duration.
402 for (p
= interp
->tstate_head
; p
!= NULL
; p
= p
->next
) {
403 if (p
->thread_id
== id
) {
404 /* Tricky: we need to decref the current value
405 * (if any) in p->async_exc, but that can in turn
406 * allow arbitrary Python code to run, including
407 * perhaps calls to this function. To prevent
408 * deadlock, we need to release head_mutex before
411 PyObject
*old_exc
= p
->async_exc
;
424 /* Routines for advanced debuggers, requested by David Beazley.
425 Don't use unless you know what you are doing! */
428 PyInterpreterState_Head(void)
434 PyInterpreterState_Next(PyInterpreterState
*interp
) {
439 PyInterpreterState_ThreadHead(PyInterpreterState
*interp
) {
440 return interp
->tstate_head
;
444 PyThreadState_Next(PyThreadState
*tstate
) {
448 /* The implementation of sys._current_frames(). This is intended to be
449 called with the GIL held, as it will be when called via
450 sys._current_frames(). It's possible it would work fine even without
451 the GIL held, but haven't thought enough about that.
454 _PyThread_CurrentFrames(void)
457 PyInterpreterState
*i
;
459 result
= PyDict_New();
463 /* for i in all interpreters:
464 * for t in all of i's thread states:
465 * if t's frame isn't NULL, map t's id to its frame
466 * Because these lists can mutute even when the GIL is held, we
467 * need to grab head_mutex for the duration.
470 for (i
= interp_head
; i
!= NULL
; i
= i
->next
) {
472 for (t
= i
->tstate_head
; t
!= NULL
; t
= t
->next
) {
475 struct _frame
*frame
= t
->frame
;
478 id
= PyInt_FromLong(t
->thread_id
);
481 stat
= PyDict_SetItem(result
, id
, (PyObject
*)frame
);
496 /* Python "auto thread state" API. */
499 /* Keep this as a static, as it is not reliable! It can only
500 ever be compared to the state for the *current* thread.
501 * If not equal, then it doesn't matter that the actual
502 value may change immediately after comparison, as it can't
503 possibly change to the current thread's state.
504 * If equal, then the current thread holds the lock, so the value can't
505 change until we yield the lock.
508 PyThreadState_IsCurrent(PyThreadState
*tstate
)
510 /* Must be the tstate for this thread */
511 assert(PyGILState_GetThisThreadState()==tstate
);
512 /* On Windows at least, simple reads and writes to 32 bit values
515 return tstate
== _PyThreadState_Current
;
518 /* Internal initialization/finalization functions called by
519 Py_Initialize/Py_Finalize
522 _PyGILState_Init(PyInterpreterState
*i
, PyThreadState
*t
)
524 assert(i
&& t
); /* must init with valid states */
525 autoTLSkey
= PyThread_create_key();
526 autoInterpreterState
= i
;
527 assert(PyThread_get_key_value(autoTLSkey
) == NULL
);
528 assert(t
->gilstate_counter
== 0);
530 _PyGILState_NoteThreadState(t
);
534 _PyGILState_Fini(void)
536 PyThread_delete_key(autoTLSkey
);
538 autoInterpreterState
= NULL
;
541 /* When a thread state is created for a thread by some mechanism other than
542 PyGILState_Ensure, it's important that the GILState machinery knows about
543 it so it doesn't try to create another thread state for the thread (this is
544 a better fix for SF bug #1010677 than the first one attempted).
547 _PyGILState_NoteThreadState(PyThreadState
* tstate
)
549 /* If autoTLSkey is 0, this must be the very first threadstate created
550 in Py_Initialize(). Don't do anything for now (we'll be back here
551 when _PyGILState_Init is called). */
555 /* Stick the thread state for this thread in thread local storage.
557 The only situation where you can legitimately have more than one
558 thread state for an OS level thread is when there are multiple
561 a) You shouldn't really be using the PyGILState_ APIs anyway,
564 b) The slightly odd way PyThread_set_key_value works (see
565 comments by its implementation) means that the first thread
566 state created for that given OS level thread will "win",
567 which seems reasonable behaviour.
569 if (PyThread_set_key_value(autoTLSkey
, (void *)tstate
) < 0)
570 Py_FatalError("Couldn't create autoTLSkey mapping");
572 /* PyGILState_Release must not try to delete this thread state. */
573 tstate
->gilstate_counter
= 1;
576 /* The public functions */
578 PyGILState_GetThisThreadState(void)
580 if (autoInterpreterState
== NULL
|| autoTLSkey
== 0)
582 return (PyThreadState
*)PyThread_get_key_value(autoTLSkey
);
586 PyGILState_Ensure(void)
590 /* Note that we do not auto-init Python here - apart from
591 potential races with 2 threads auto-initializing, pep-311
592 spells out other issues. Embedders are expected to have
593 called Py_Initialize() and usually PyEval_InitThreads().
595 assert(autoInterpreterState
); /* Py_Initialize() hasn't been called! */
596 tcur
= (PyThreadState
*)PyThread_get_key_value(autoTLSkey
);
598 /* Create a new thread state for this thread */
599 tcur
= PyThreadState_New(autoInterpreterState
);
601 Py_FatalError("Couldn't create thread-state for new thread");
602 /* This is our thread state! We'll need to delete it in the
603 matching call to PyGILState_Release(). */
604 tcur
->gilstate_counter
= 0;
605 current
= 0; /* new thread state is never current */
608 current
= PyThreadState_IsCurrent(tcur
);
610 PyEval_RestoreThread(tcur
);
611 /* Update our counter in the thread-state - no need for locks:
612 - tcur will remain valid as we hold the GIL.
613 - the counter is safe as we are the only thread "allowed"
616 ++tcur
->gilstate_counter
;
617 return current
? PyGILState_LOCKED
: PyGILState_UNLOCKED
;
621 PyGILState_Release(PyGILState_STATE oldstate
)
623 PyThreadState
*tcur
= (PyThreadState
*)PyThread_get_key_value(
626 Py_FatalError("auto-releasing thread-state, "
627 "but no thread-state for this thread");
628 /* We must hold the GIL and have our thread state current */
629 /* XXX - remove the check - the assert should be fine,
630 but while this is very new (April 2003), the extra check
631 by release-only users can't hurt.
633 if (! PyThreadState_IsCurrent(tcur
))
634 Py_FatalError("This thread state must be current when releasing");
635 assert(PyThreadState_IsCurrent(tcur
));
636 --tcur
->gilstate_counter
;
637 assert(tcur
->gilstate_counter
>= 0); /* illegal counter value */
639 /* If we're going to destroy this thread-state, we must
640 * clear it while the GIL is held, as destructors may run.
642 if (tcur
->gilstate_counter
== 0) {
643 /* can't have been locked when we created it */
644 assert(oldstate
== PyGILState_UNLOCKED
);
645 PyThreadState_Clear(tcur
);
646 /* Delete the thread-state. Note this releases the GIL too!
647 * It's vital that the GIL be held here, to avoid shutdown
648 * races; see bugs 225673 and 1061968 (that nasty bug has a
649 * habit of coming back).
651 PyThreadState_DeleteCurrent();
653 /* Release the lock if necessary */
654 else if (oldstate
== PyGILState_UNLOCKED
)
662 #endif /* WITH_THREAD */