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 -------------------------------------------------------------------------- */
27 PyObject *tmp = (PyObject *)(x); \
35 static PyThread_type_lock head_mutex
= NULL
; /* Protects interp->tstate_head */
36 #define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
37 #define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
38 #define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
40 /* The single PyInterpreterState used by this process'
41 GILState implementation
43 static PyInterpreterState
*autoInterpreterState
= NULL
;
44 static int autoTLSkey
= 0;
46 #define HEAD_INIT() /* Nothing */
47 #define HEAD_LOCK() /* Nothing */
48 #define HEAD_UNLOCK() /* Nothing */
51 static PyInterpreterState
*interp_head
= NULL
;
53 PyThreadState
*_PyThreadState_Current
= NULL
;
54 PyThreadFrameGetter _PyThreadState_GetFrame
= NULL
;
57 static void _PyGILState_NoteThreadState(PyThreadState
* tstate
);
62 PyInterpreterState_New(void)
64 PyInterpreterState
*interp
= (PyInterpreterState
*)
65 malloc(sizeof(PyInterpreterState
));
69 interp
->modules
= NULL
;
70 interp
->sysdict
= NULL
;
71 interp
->builtins
= NULL
;
72 interp
->tstate_head
= NULL
;
73 interp
->codec_search_path
= NULL
;
74 interp
->codec_search_cache
= NULL
;
75 interp
->codec_error_registry
= NULL
;
78 interp
->dlopenflags
= RTLD_NOW
;
80 interp
->dlopenflags
= RTLD_LAZY
;
88 interp
->next
= interp_head
;
98 PyInterpreterState_Clear(PyInterpreterState
*interp
)
102 for (p
= interp
->tstate_head
; p
!= NULL
; p
= p
->next
)
103 PyThreadState_Clear(p
);
105 ZAP(interp
->codec_search_path
);
106 ZAP(interp
->codec_search_cache
);
107 ZAP(interp
->codec_error_registry
);
108 ZAP(interp
->modules
);
109 ZAP(interp
->sysdict
);
110 ZAP(interp
->builtins
);
115 zapthreads(PyInterpreterState
*interp
)
118 /* No need to lock the mutex here because this should only happen
119 when the threads are all really dead (XXX famous last words). */
120 while ((p
= interp
->tstate_head
) != NULL
) {
121 PyThreadState_Delete(p
);
127 PyInterpreterState_Delete(PyInterpreterState
*interp
)
129 PyInterpreterState
**p
;
132 for (p
= &interp_head
; ; p
= &(*p
)->next
) {
135 "PyInterpreterState_Delete: invalid interp");
139 if (interp
->tstate_head
!= NULL
)
140 Py_FatalError("PyInterpreterState_Delete: remaining threads");
147 /* Default implementation for _PyThreadState_GetFrame */
148 static struct _frame
*
149 threadstate_getframe(PyThreadState
*self
)
155 PyThreadState_New(PyInterpreterState
*interp
)
157 PyThreadState
*tstate
= (PyThreadState
*)malloc(sizeof(PyThreadState
));
159 if (_PyThreadState_GetFrame
== NULL
)
160 _PyThreadState_GetFrame
= threadstate_getframe
;
162 if (tstate
!= NULL
) {
163 tstate
->interp
= interp
;
165 tstate
->frame
= NULL
;
166 tstate
->recursion_depth
= 0;
168 tstate
->use_tracing
= 0;
169 tstate
->tick_counter
= 0;
170 tstate
->gilstate_counter
= 0;
171 tstate
->async_exc
= NULL
;
173 tstate
->thread_id
= PyThread_get_thread_ident();
175 tstate
->thread_id
= 0;
180 tstate
->curexc_type
= NULL
;
181 tstate
->curexc_value
= NULL
;
182 tstate
->curexc_traceback
= NULL
;
184 tstate
->exc_type
= NULL
;
185 tstate
->exc_value
= NULL
;
186 tstate
->exc_traceback
= NULL
;
188 tstate
->c_profilefunc
= NULL
;
189 tstate
->c_tracefunc
= NULL
;
190 tstate
->c_profileobj
= NULL
;
191 tstate
->c_traceobj
= NULL
;
194 _PyGILState_NoteThreadState(tstate
);
198 tstate
->next
= interp
->tstate_head
;
199 interp
->tstate_head
= tstate
;
208 PyThreadState_Clear(PyThreadState
*tstate
)
210 if (Py_VerboseFlag
&& tstate
->frame
!= NULL
)
212 "PyThreadState_Clear: warning: thread still has a frame\n");
217 ZAP(tstate
->async_exc
);
219 ZAP(tstate
->curexc_type
);
220 ZAP(tstate
->curexc_value
);
221 ZAP(tstate
->curexc_traceback
);
223 ZAP(tstate
->exc_type
);
224 ZAP(tstate
->exc_value
);
225 ZAP(tstate
->exc_traceback
);
227 tstate
->c_profilefunc
= NULL
;
228 tstate
->c_tracefunc
= NULL
;
229 ZAP(tstate
->c_profileobj
);
230 ZAP(tstate
->c_traceobj
);
234 /* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
236 tstate_delete_common(PyThreadState
*tstate
)
238 PyInterpreterState
*interp
;
241 Py_FatalError("PyThreadState_Delete: NULL tstate");
242 interp
= tstate
->interp
;
244 Py_FatalError("PyThreadState_Delete: NULL interp");
246 for (p
= &interp
->tstate_head
; ; p
= &(*p
)->next
) {
249 "PyThreadState_Delete: invalid tstate");
260 PyThreadState_Delete(PyThreadState
*tstate
)
262 if (tstate
== _PyThreadState_Current
)
263 Py_FatalError("PyThreadState_Delete: tstate is still current");
264 tstate_delete_common(tstate
);
266 if (autoTLSkey
&& PyThread_get_key_value(autoTLSkey
) == tstate
)
267 PyThread_delete_key_value(autoTLSkey
);
268 #endif /* WITH_THREAD */
274 PyThreadState_DeleteCurrent()
276 PyThreadState
*tstate
= _PyThreadState_Current
;
279 "PyThreadState_DeleteCurrent: no current tstate");
280 _PyThreadState_Current
= NULL
;
281 tstate_delete_common(tstate
);
282 if (autoTLSkey
&& PyThread_get_key_value(autoTLSkey
) == tstate
)
283 PyThread_delete_key_value(autoTLSkey
);
284 PyEval_ReleaseLock();
286 #endif /* WITH_THREAD */
290 PyThreadState_Get(void)
292 if (_PyThreadState_Current
== NULL
)
293 Py_FatalError("PyThreadState_Get: no current thread");
295 return _PyThreadState_Current
;
300 PyThreadState_Swap(PyThreadState
*new)
302 PyThreadState
*old
= _PyThreadState_Current
;
304 _PyThreadState_Current
= new;
305 /* It should not be possible for more than one thread state
306 to be used for a thread. Check this the best we can in debug
309 #if defined(Py_DEBUG) && defined(WITH_THREAD)
311 PyThreadState
*check
= PyGILState_GetThisThreadState();
312 if (check
&& check
->interp
== new->interp
&& check
!= new)
313 Py_FatalError("Invalid thread state for this thread");
319 /* An extension mechanism to store arbitrary additional per-thread state.
320 PyThreadState_GetDict() returns a dictionary that can be used to hold such
321 state; the caller should pick a unique key and store its state there. If
322 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
323 and the caller should assume no per-thread state is available. */
326 PyThreadState_GetDict(void)
328 if (_PyThreadState_Current
== NULL
)
331 if (_PyThreadState_Current
->dict
== NULL
) {
333 _PyThreadState_Current
->dict
= d
= PyDict_New();
337 return _PyThreadState_Current
->dict
;
341 /* Asynchronously raise an exception in a thread.
342 Requested by Just van Rossum and Alex Martelli.
343 To prevent naive misuse, you must write your own extension
344 to call this. Must be called with the GIL held.
345 Returns the number of tstates modified; if it returns a number
346 greater than one, you're in trouble, and you should call it again
347 with exc=NULL to revert the effect. This raises no exceptions. */
350 PyThreadState_SetAsyncExc(long id
, PyObject
*exc
) {
351 PyThreadState
*tstate
= PyThreadState_GET();
352 PyInterpreterState
*interp
= tstate
->interp
;
356 for (p
= interp
->tstate_head
; p
!= NULL
; p
= p
->next
) {
357 if (p
->thread_id
!= id
)
369 /* Routines for advanced debuggers, requested by David Beazley.
370 Don't use unless you know what you are doing! */
373 PyInterpreterState_Head(void)
379 PyInterpreterState_Next(PyInterpreterState
*interp
) {
384 PyInterpreterState_ThreadHead(PyInterpreterState
*interp
) {
385 return interp
->tstate_head
;
389 PyThreadState_Next(PyThreadState
*tstate
) {
394 /* Python "auto thread state" API. */
397 /* Keep this as a static, as it is not reliable! It can only
398 ever be compared to the state for the *current* thread.
399 * If not equal, then it doesn't matter that the actual
400 value may change immediately after comparison, as it can't
401 possibly change to the current thread's state.
402 * If equal, then the current thread holds the lock, so the value can't
403 change until we yield the lock.
406 PyThreadState_IsCurrent(PyThreadState
*tstate
)
408 /* Must be the tstate for this thread */
409 assert(PyGILState_GetThisThreadState()==tstate
);
410 /* On Windows at least, simple reads and writes to 32 bit values
413 return tstate
== _PyThreadState_Current
;
416 /* Internal initialization/finalization functions called by
417 Py_Initialize/Py_Finalize
420 _PyGILState_Init(PyInterpreterState
*i
, PyThreadState
*t
)
422 assert(i
&& t
); /* must init with valid states */
423 autoTLSkey
= PyThread_create_key();
424 autoInterpreterState
= i
;
425 assert(PyThread_get_key_value(autoTLSkey
) == NULL
);
426 assert(t
->gilstate_counter
== 0);
428 _PyGILState_NoteThreadState(t
);
432 _PyGILState_Fini(void)
434 PyThread_delete_key(autoTLSkey
);
436 autoInterpreterState
= NULL
;;
439 /* When a thread state is created for a thread by some mechanism other than
440 PyGILState_Ensure, it's important that the GILState machinery knows about
441 it so it doesn't try to create another thread state for the thread (this is
442 a better fix for SF bug #1010677 than the first one attempted).
445 _PyGILState_NoteThreadState(PyThreadState
* tstate
)
447 /* If autoTLSkey is 0, this must be the very first threadstate created
448 in Py_Initialize(). Don't do anything for now (we'll be back here
449 when _PyGILState_Init is called). */
453 /* Stick the thread state for this thread in thread local storage.
455 The only situation where you can legitimately have more than one
456 thread state for an OS level thread is when there are multiple
459 a) You shouldn't really be using the PyGILState_ APIs anyway,
462 b) The slightly odd way PyThread_set_key_value works (see
463 comments by its implementation) means that the first thread
464 state created for that given OS level thread will "win",
465 which seems reasonable behaviour.
467 if (PyThread_set_key_value(autoTLSkey
, (void *)tstate
) < 0)
468 Py_FatalError("Couldn't create autoTLSkey mapping");
470 /* PyGILState_Release must not try to delete this thread state. */
471 tstate
->gilstate_counter
= 1;
474 /* The public functions */
476 PyGILState_GetThisThreadState(void)
478 if (autoInterpreterState
== NULL
|| autoTLSkey
== 0)
480 return (PyThreadState
*)PyThread_get_key_value(autoTLSkey
);
484 PyGILState_Ensure(void)
488 /* Note that we do not auto-init Python here - apart from
489 potential races with 2 threads auto-initializing, pep-311
490 spells out other issues. Embedders are expected to have
491 called Py_Initialize() and usually PyEval_InitThreads().
493 assert(autoInterpreterState
); /* Py_Initialize() hasn't been called! */
494 tcur
= PyThread_get_key_value(autoTLSkey
);
496 /* Create a new thread state for this thread */
497 tcur
= PyThreadState_New(autoInterpreterState
);
499 Py_FatalError("Couldn't create thread-state for new thread");
500 /* This is our thread state! We'll need to delete it in the
501 matching call to PyGILState_Release(). */
502 tcur
->gilstate_counter
= 0;
503 current
= 0; /* new thread state is never current */
506 current
= PyThreadState_IsCurrent(tcur
);
508 PyEval_RestoreThread(tcur
);
509 /* Update our counter in the thread-state - no need for locks:
510 - tcur will remain valid as we hold the GIL.
511 - the counter is safe as we are the only thread "allowed"
514 ++tcur
->gilstate_counter
;
515 return current
? PyGILState_LOCKED
: PyGILState_UNLOCKED
;
519 PyGILState_Release(PyGILState_STATE oldstate
)
521 PyThreadState
*tcur
= PyThread_get_key_value(autoTLSkey
);
523 Py_FatalError("auto-releasing thread-state, "
524 "but no thread-state for this thread");
525 /* We must hold the GIL and have our thread state current */
526 /* XXX - remove the check - the assert should be fine,
527 but while this is very new (April 2003), the extra check
528 by release-only users can't hurt.
530 if (! PyThreadState_IsCurrent(tcur
))
531 Py_FatalError("This thread state must be current when releasing");
532 assert(PyThreadState_IsCurrent(tcur
));
533 --tcur
->gilstate_counter
;
534 assert(tcur
->gilstate_counter
>= 0); /* illegal counter value */
536 /* If we're going to destroy this thread-state, we must
537 * clear it while the GIL is held, as destructors may run.
539 if (tcur
->gilstate_counter
== 0) {
540 /* can't have been locked when we created it */
541 assert(oldstate
== PyGILState_UNLOCKED
);
542 PyThreadState_Clear(tcur
);
543 /* Delete the thread-state. Note this releases the GIL too!
544 * It's vital that the GIL be held here, to avoid shutdown
545 * races; see bugs 225673 and 1061968 (that nasty bug has a
546 * habit of coming back).
548 PyThreadState_DeleteCurrent();
550 /* Release the lock if necessary */
551 else if (oldstate
== PyGILState_UNLOCKED
)
554 #endif /* WITH_THREAD */