blob: b1aececd6faa08257569cd7a5b42b458670b7bff [file] [log] [blame]
Guido van Rossuma027efa1997-05-05 20:56:21 +00001
2/* Thread and interpreter state structures and their interfaces */
3
4#include "Python.h"
5
Victor Stinnerb02ef712016-01-22 14:09:55 +01006#define GET_TSTATE() \
7 ((PyThreadState*)_Py_atomic_load_relaxed(&_PyThreadState_Current))
8#define SET_TSTATE(value) \
9 _Py_atomic_store_relaxed(&_PyThreadState_Current, (Py_uintptr_t)(value))
10#define GET_INTERP_STATE() \
11 (GET_TSTATE()->interp)
12
Victor Stinnerbfd316e2016-01-20 11:12:38 +010013
Tim Peters84705582004-10-10 02:47:33 +000014/* --------------------------------------------------------------------------
15CAUTION
16
Victor Stinner1a7425f2013-07-07 16:25:15 +020017Always use PyMem_RawMalloc() and PyMem_RawFree() directly in this file. A
18number of these functions are advertised as safe to call when the GIL isn't
19held, and in a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's
20debugging obmalloc functions. Those aren't thread-safe (they rely on the GIL
21to avoid the expense of doing their own locking).
Tim Peters84705582004-10-10 02:47:33 +000022-------------------------------------------------------------------------- */
23
Martin v. Löwisf0473d52001-07-18 16:17:16 +000024#ifdef HAVE_DLOPEN
25#ifdef HAVE_DLFCN_H
26#include <dlfcn.h>
27#endif
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030028#if !HAVE_DECL_RTLD_LAZY
Martin v. Löwisf0473d52001-07-18 16:17:16 +000029#define RTLD_LAZY 1
30#endif
31#endif
32
Benjamin Peterson43162b82012-04-13 11:58:27 -040033#ifdef __cplusplus
34extern "C" {
35#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +000036
Victor Stinner8a1be612016-03-14 22:07:55 +010037int _PyGILState_check_enabled = 1;
38
Guido van Rossum1d5ad901999-06-18 14:22:24 +000039#ifdef WITH_THREAD
40#include "pythread.h"
41static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
Moshe Zadka9fb6af92000-08-04 21:27:47 +000042#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
Guido van Rossum1d5ad901999-06-18 14:22:24 +000043#define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
44#define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
Michael W. Hudson188d4362005-06-20 16:52:57 +000045
46/* The single PyInterpreterState used by this process'
47 GILState implementation
48*/
49static PyInterpreterState *autoInterpreterState = NULL;
Victor Stinner8a1be612016-03-14 22:07:55 +010050static int autoTLSkey = -1;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000051#else
52#define HEAD_INIT() /* Nothing */
53#define HEAD_LOCK() /* Nothing */
54#define HEAD_UNLOCK() /* Nothing */
55#endif
56
Guido van Rossum25ce5661997-08-02 03:10:38 +000057static PyInterpreterState *interp_head = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000058
Jeffrey Yasskin39370832010-05-03 19:29:34 +000059/* Assuming the current thread holds the GIL, this is the
60 PyThreadState for the current thread. */
Victor Stinnerb02ef712016-01-22 14:09:55 +010061_Py_atomic_address _PyThreadState_Current = {0};
Guido van Rossum6297a7a2003-02-19 15:53:17 +000062PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000063
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000064#ifdef WITH_THREAD
Michael W. Hudson188d4362005-06-20 16:52:57 +000065static void _PyGILState_NoteThreadState(PyThreadState* tstate);
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000066#endif
Michael W. Hudson188d4362005-06-20 16:52:57 +000067
Guido van Rossuma027efa1997-05-05 20:56:21 +000068
69PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000070PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 PyInterpreterState *interp = (PyInterpreterState *)
Victor Stinner1a7425f2013-07-07 16:25:15 +020073 PyMem_RawMalloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +000074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 if (interp != NULL) {
76 HEAD_INIT();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000077#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (head_mutex == NULL)
79 Py_FatalError("Can't initialize threads for interpreter");
Thomas Wouters0e3f5912006-08-11 14:57:12 +000080#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000081 interp->modules = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000082 interp->modules_by_index = NULL;
83 interp->sysdict = NULL;
84 interp->builtins = NULL;
Serhiy Storchaka87a5c512014-02-10 18:21:34 +020085 interp->builtins_copy = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000086 interp->tstate_head = NULL;
87 interp->codec_search_path = NULL;
88 interp->codec_search_cache = NULL;
89 interp->codec_error_registry = NULL;
90 interp->codecs_initialized = 0;
Victor Stinner3cbf14b2011-04-27 00:24:21 +020091 interp->fscodec_initialized = 0;
Brett Cannonfd074152012-04-14 14:10:13 -040092 interp->importlib = NULL;
Serhiy Storchaka133138a2016-08-02 22:51:21 +030093 interp->import_func = NULL;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000094#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030095#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000096 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000097#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000099#endif
100#endif
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000101#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 interp->tscdump = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000103#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 HEAD_LOCK();
106 interp->next = interp_head;
107 interp_head = interp;
108 HEAD_UNLOCK();
109 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000112}
113
114
115void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000116PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000117{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000118 PyThreadState *p;
119 HEAD_LOCK();
120 for (p = interp->tstate_head; p != NULL; p = p->next)
121 PyThreadState_Clear(p);
122 HEAD_UNLOCK();
123 Py_CLEAR(interp->codec_search_path);
124 Py_CLEAR(interp->codec_search_cache);
125 Py_CLEAR(interp->codec_error_registry);
126 Py_CLEAR(interp->modules);
127 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000128 Py_CLEAR(interp->sysdict);
129 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200130 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400131 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300132 Py_CLEAR(interp->import_func);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000133}
134
135
136static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000137zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 PyThreadState *p;
140 /* No need to lock the mutex here because this should only happen
141 when the threads are all really dead (XXX famous last words). */
142 while ((p = interp->tstate_head) != NULL) {
143 PyThreadState_Delete(p);
144 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000145}
146
147
148void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000149PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000151 PyInterpreterState **p;
152 zapthreads(interp);
153 HEAD_LOCK();
154 for (p = &interp_head; ; p = &(*p)->next) {
155 if (*p == NULL)
156 Py_FatalError(
157 "PyInterpreterState_Delete: invalid interp");
158 if (*p == interp)
159 break;
160 }
161 if (interp->tstate_head != NULL)
162 Py_FatalError("PyInterpreterState_Delete: remaining threads");
163 *p = interp->next;
164 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200165 PyMem_RawFree(interp);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100166#ifdef WITH_THREAD
167 if (interp_head == NULL && head_mutex != NULL) {
168 PyThread_free_lock(head_mutex);
169 head_mutex = NULL;
170 }
171#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000172}
173
174
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000175/* Default implementation for _PyThreadState_GetFrame */
176static struct _frame *
177threadstate_getframe(PyThreadState *self)
178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000180}
181
Victor Stinner45b9be52010-03-03 23:28:07 +0000182static PyThreadState *
183new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000184{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200185 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (_PyThreadState_GetFrame == NULL)
188 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 if (tstate != NULL) {
191 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 tstate->frame = NULL;
194 tstate->recursion_depth = 0;
195 tstate->overflowed = 0;
196 tstate->recursion_critical = 0;
197 tstate->tracing = 0;
198 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000199 tstate->gilstate_counter = 0;
200 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000201#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000203#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000205#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 tstate->curexc_type = NULL;
210 tstate->curexc_value = NULL;
211 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 tstate->exc_type = NULL;
214 tstate->exc_value = NULL;
215 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 tstate->c_profilefunc = NULL;
218 tstate->c_tracefunc = NULL;
219 tstate->c_profileobj = NULL;
220 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000221
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200222 tstate->trash_delete_nesting = 0;
223 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200224 tstate->on_delete = NULL;
225 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200226
Yury Selivanov75445082015-05-11 22:57:16 -0400227 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400228 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (init)
231 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000233 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200234 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200236 if (tstate->next)
237 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 interp->tstate_head = tstate;
239 HEAD_UNLOCK();
240 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000243}
244
Victor Stinner45b9be52010-03-03 23:28:07 +0000245PyThreadState *
246PyThreadState_New(PyInterpreterState *interp)
247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000249}
250
251PyThreadState *
252_PyThreadState_Prealloc(PyInterpreterState *interp)
253{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000254 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000255}
256
257void
258_PyThreadState_Init(PyThreadState *tstate)
259{
260#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000262#endif
263}
264
Martin v. Löwis1a214512008-06-11 05:26:20 +0000265PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200266PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000267{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200268 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100269 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000271 if (module->m_slots) {
272 return NULL;
273 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (index == 0)
275 return NULL;
276 if (state->modules_by_index == NULL)
277 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200278 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 return NULL;
280 res = PyList_GET_ITEM(state->modules_by_index, index);
281 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000282}
283
284int
285_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
286{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000287 PyInterpreterState *state;
288 if (def->m_slots) {
289 PyErr_SetString(PyExc_SystemError,
290 "PyState_AddModule called on module with slots");
291 return -1;
292 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100293 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 if (!def)
295 return -1;
296 if (!state->modules_by_index) {
297 state->modules_by_index = PyList_New(0);
298 if (!state->modules_by_index)
299 return -1;
300 }
301 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
302 if (PyList_Append(state->modules_by_index, Py_None) < 0)
303 return -1;
304 Py_INCREF(module);
305 return PyList_SetItem(state->modules_by_index,
306 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000307}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000308
Martin v. Löwis7800f752012-06-22 12:20:55 +0200309int
310PyState_AddModule(PyObject* module, struct PyModuleDef* def)
311{
312 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100313 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200314 if (!def) {
315 Py_FatalError("PyState_AddModule: Module Definition is NULL");
316 return -1;
317 }
318 index = def->m_base.m_index;
319 if (state->modules_by_index) {
320 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
321 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
322 Py_FatalError("PyState_AddModule: Module already added!");
323 return -1;
324 }
325 }
326 }
327 return _PyState_AddModule(module, def);
328}
329
330int
331PyState_RemoveModule(struct PyModuleDef* def)
332{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000333 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200334 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000335 if (def->m_slots) {
336 PyErr_SetString(PyExc_SystemError,
337 "PyState_RemoveModule called on module with slots");
338 return -1;
339 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100340 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200341 if (index == 0) {
342 Py_FatalError("PyState_RemoveModule: Module index invalid.");
343 return -1;
344 }
345 if (state->modules_by_index == NULL) {
346 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
347 return -1;
348 }
349 if (index > PyList_GET_SIZE(state->modules_by_index)) {
350 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
351 return -1;
352 }
353 return PyList_SetItem(state->modules_by_index, index, Py_None);
354}
355
Antoine Pitrou40322e62013-08-11 00:30:09 +0200356/* used by import.c:PyImport_Cleanup */
357void
358_PyState_ClearModules(void)
359{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100360 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200361 if (state->modules_by_index) {
362 Py_ssize_t i;
363 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
364 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
365 if (PyModule_Check(m)) {
366 /* cleanup the saved copy of module dicts */
367 PyModuleDef *md = PyModule_GetDef(m);
368 if (md)
369 Py_CLEAR(md->m_base.m_copy);
370 }
371 }
372 /* Setting modules_by_index to NULL could be dangerous, so we
373 clear the list instead. */
374 if (PyList_SetSlice(state->modules_by_index,
375 0, PyList_GET_SIZE(state->modules_by_index),
376 NULL))
377 PyErr_WriteUnraisable(state->modules_by_index);
378 }
379}
380
Guido van Rossuma027efa1997-05-05 20:56:21 +0000381void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000382PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (Py_VerboseFlag && tstate->frame != NULL)
385 fprintf(stderr,
386 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 Py_CLEAR(tstate->dict);
391 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_CLEAR(tstate->curexc_type);
394 Py_CLEAR(tstate->curexc_value);
395 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 Py_CLEAR(tstate->exc_type);
398 Py_CLEAR(tstate->exc_value);
399 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 tstate->c_profilefunc = NULL;
402 tstate->c_tracefunc = NULL;
403 Py_CLEAR(tstate->c_profileobj);
404 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400405
406 Py_CLEAR(tstate->coroutine_wrapper);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000407}
408
409
Guido van Rossum29757862001-01-23 01:46:06 +0000410/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
411static void
412tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (tstate == NULL)
416 Py_FatalError("PyThreadState_Delete: NULL tstate");
417 interp = tstate->interp;
418 if (interp == NULL)
419 Py_FatalError("PyThreadState_Delete: NULL interp");
420 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200421 if (tstate->prev)
422 tstate->prev->next = tstate->next;
423 else
424 interp->tstate_head = tstate->next;
425 if (tstate->next)
426 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200428 if (tstate->on_delete != NULL) {
429 tstate->on_delete(tstate->on_delete_data);
430 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200431 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000432}
433
434
Guido van Rossum29757862001-01-23 01:46:06 +0000435void
436PyThreadState_Delete(PyThreadState *tstate)
437{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100438 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 Py_FatalError("PyThreadState_Delete: tstate is still current");
Tim Petersf4e69282006-02-27 17:15:31 +0000440#ifdef WITH_THREAD
Antoine Pitrou079ce542010-09-08 12:37:10 +0000441 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 PyThread_delete_key_value(autoTLSkey);
Tim Petersf4e69282006-02-27 17:15:31 +0000443#endif /* WITH_THREAD */
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200444 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000445}
446
447
448#ifdef WITH_THREAD
449void
450PyThreadState_DeleteCurrent()
451{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100452 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (tstate == NULL)
454 Py_FatalError(
455 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100456 tstate_delete_common(tstate);
Antoine Pitrou079ce542010-09-08 12:37:10 +0000457 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyThread_delete_key_value(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100459 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000461}
462#endif /* WITH_THREAD */
463
464
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200465/*
466 * Delete all thread states except the one passed as argument.
467 * Note that, if there is a current thread state, it *must* be the one
468 * passed as argument. Also, this won't touch any other interpreters
469 * than the current one, since we don't know which thread state should
470 * be kept in those other interpreteres.
471 */
472void
473_PyThreadState_DeleteExcept(PyThreadState *tstate)
474{
475 PyInterpreterState *interp = tstate->interp;
476 PyThreadState *p, *next, *garbage;
477 HEAD_LOCK();
478 /* Remove all thread states, except tstate, from the linked list of
479 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200480 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200481 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200482 if (garbage == tstate)
483 garbage = tstate->next;
484 if (tstate->prev)
485 tstate->prev->next = tstate->next;
486 if (tstate->next)
487 tstate->next->prev = tstate->prev;
488 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200489 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200490 HEAD_UNLOCK();
491 /* Clear and deallocate all stale thread states. Even if this
492 executes Python code, we should be safe since it executes
493 in the current thread, not one of the stale threads. */
494 for (p = garbage; p; p = next) {
495 next = p->next;
496 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200497 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200498 }
499}
500
501
Guido van Rossuma027efa1997-05-05 20:56:21 +0000502PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100503_PyThreadState_UncheckedGet(void)
504{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100505 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100506}
507
508
509PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000510PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000511{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100512 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (tstate == NULL)
514 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000517}
518
519
520PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000521PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000522{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100523 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000524
Victor Stinnerb02ef712016-01-22 14:09:55 +0100525 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 /* It should not be possible for more than one thread state
527 to be used for a thread. Check this the best we can in debug
528 builds.
529 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000530#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (newts) {
532 /* This can be called from PyEval_RestoreThread(). Similar
533 to it, we need to ensure errno doesn't change.
534 */
535 int err = errno;
536 PyThreadState *check = PyGILState_GetThisThreadState();
537 if (check && check->interp == newts->interp && check != newts)
538 Py_FatalError("Invalid thread state for this thread");
539 errno = err;
540 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000541#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000543}
Guido van Rossumede04391998-04-10 20:18:25 +0000544
545/* An extension mechanism to store arbitrary additional per-thread state.
546 PyThreadState_GetDict() returns a dictionary that can be used to hold such
547 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000548 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
549 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000550
551PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000552PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000553{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100554 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 if (tstate == NULL)
556 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (tstate->dict == NULL) {
559 PyObject *d;
560 tstate->dict = d = PyDict_New();
561 if (d == NULL)
562 PyErr_Clear();
563 }
564 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000565}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000566
567
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000568/* Asynchronously raise an exception in a thread.
569 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000570 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000571 to call this, or use ctypes. Must be called with the GIL held.
572 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
573 match any known thread id). Can be called with exc=NULL to clear an
574 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000575
576int
577PyThreadState_SetAsyncExc(long id, PyObject *exc) {
Victor Stinnerb02ef712016-01-22 14:09:55 +0100578 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000579 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 /* Although the GIL is held, a few C API functions can be called
582 * without the GIL held, and in particular some that create and
583 * destroy thread and interpreter states. Those can mutate the
584 * list of thread states we're traversing, so to prevent that we lock
585 * head_mutex for the duration.
586 */
587 HEAD_LOCK();
588 for (p = interp->tstate_head; p != NULL; p = p->next) {
589 if (p->thread_id == id) {
590 /* Tricky: we need to decref the current value
591 * (if any) in p->async_exc, but that can in turn
592 * allow arbitrary Python code to run, including
593 * perhaps calls to this function. To prevent
594 * deadlock, we need to release head_mutex before
595 * the decref.
596 */
597 PyObject *old_exc = p->async_exc;
598 Py_XINCREF(exc);
599 p->async_exc = exc;
600 HEAD_UNLOCK();
601 Py_XDECREF(old_exc);
602 _PyEval_SignalAsyncExc();
603 return 1;
604 }
605 }
606 HEAD_UNLOCK();
607 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000608}
609
610
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000611/* Routines for advanced debuggers, requested by David Beazley.
612 Don't use unless you know what you are doing! */
613
614PyInterpreterState *
615PyInterpreterState_Head(void)
616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 return interp_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000618}
619
620PyInterpreterState *
621PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000623}
624
625PyThreadState *
626PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000628}
629
630PyThreadState *
631PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000633}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000634
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000635/* The implementation of sys._current_frames(). This is intended to be
636 called with the GIL held, as it will be when called via
637 sys._current_frames(). It's possible it would work fine even without
638 the GIL held, but haven't thought enough about that.
639*/
640PyObject *
641_PyThread_CurrentFrames(void)
642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyObject *result;
644 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 result = PyDict_New();
647 if (result == NULL)
648 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000649
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 /* for i in all interpreters:
651 * for t in all of i's thread states:
652 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200653 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000654 * need to grab head_mutex for the duration.
655 */
656 HEAD_LOCK();
657 for (i = interp_head; i != NULL; i = i->next) {
658 PyThreadState *t;
659 for (t = i->tstate_head; t != NULL; t = t->next) {
660 PyObject *id;
661 int stat;
662 struct _frame *frame = t->frame;
663 if (frame == NULL)
664 continue;
665 id = PyLong_FromLong(t->thread_id);
666 if (id == NULL)
667 goto Fail;
668 stat = PyDict_SetItem(result, id, (PyObject *)frame);
669 Py_DECREF(id);
670 if (stat < 0)
671 goto Fail;
672 }
673 }
674 HEAD_UNLOCK();
675 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000676
677 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000678 HEAD_UNLOCK();
679 Py_DECREF(result);
680 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000681}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000682
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000683/* Python "auto thread state" API. */
684#ifdef WITH_THREAD
685
686/* Keep this as a static, as it is not reliable! It can only
687 ever be compared to the state for the *current* thread.
688 * If not equal, then it doesn't matter that the actual
689 value may change immediately after comparison, as it can't
690 possibly change to the current thread's state.
691 * If equal, then the current thread holds the lock, so the value can't
692 change until we yield the lock.
693*/
694static int
695PyThreadState_IsCurrent(PyThreadState *tstate)
696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 /* Must be the tstate for this thread */
698 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100699 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000700}
701
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000702/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000703 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000704*/
Tim Peters19717fa2004-10-09 17:38:29 +0000705void
706_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 assert(i && t); /* must init with valid states */
709 autoTLSkey = PyThread_create_key();
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000710 if (autoTLSkey == -1)
711 Py_FatalError("Could not allocate TLS entry");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 autoInterpreterState = i;
713 assert(PyThread_get_key_value(autoTLSkey) == NULL);
714 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000717}
718
Victor Stinner861d9ab2016-03-16 22:45:24 +0100719PyInterpreterState *
720_PyGILState_GetInterpreterStateUnsafe(void)
721{
722 return autoInterpreterState;
723}
724
Tim Peters19717fa2004-10-09 17:38:29 +0000725void
726_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000727{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 PyThread_delete_key(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100729 autoTLSkey = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000731}
732
Charles-François Natalia233df82011-11-22 19:49:51 +0100733/* Reset the TLS key - called by PyOS_AfterFork().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200734 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100735 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200736 */
737void
738_PyGILState_Reinit(void)
739{
740 PyThreadState *tstate = PyGILState_GetThisThreadState();
741 PyThread_delete_key(autoTLSkey);
742 if ((autoTLSkey = PyThread_create_key()) == -1)
743 Py_FatalError("Could not allocate TLS entry");
744
Charles-François Natalia233df82011-11-22 19:49:51 +0100745 /* If the thread had an associated auto thread state, reassociate it with
746 * the new key. */
747 if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200748 Py_FatalError("Couldn't create autoTLSkey mapping");
749}
750
Michael W. Hudson188d4362005-06-20 16:52:57 +0000751/* When a thread state is created for a thread by some mechanism other than
752 PyGILState_Ensure, it's important that the GILState machinery knows about
753 it so it doesn't try to create another thread state for the thread (this is
754 a better fix for SF bug #1010677 than the first one attempted).
755*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000756static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000757_PyGILState_NoteThreadState(PyThreadState* tstate)
758{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000759 /* If autoTLSkey isn't initialized, this must be the very first
760 threadstate created in Py_Initialize(). Don't do anything for now
761 (we'll be back here when _PyGILState_Init is called). */
762 if (!autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000766
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 The only situation where you can legitimately have more than one
768 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100769 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000770
Victor Stinner590cebe2013-12-13 11:08:56 +0100771 You shouldn't really be using the PyGILState_ APIs anyway (see issues
772 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000773
Victor Stinner590cebe2013-12-13 11:08:56 +0100774 The first thread state created for that given OS level thread will
775 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 */
Victor Stinner590cebe2013-12-13 11:08:56 +0100777 if (PyThread_get_key_value(autoTLSkey) == NULL) {
778 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
779 Py_FatalError("Couldn't create autoTLSkey mapping");
780 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 /* PyGILState_Release must not try to delete this thread state. */
783 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000784}
785
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000786/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000787PyThreadState *
788PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000789{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000790 if (autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 return NULL;
792 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000793}
794
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700795int
796PyGILState_Check(void)
797{
Victor Stinner8a1be612016-03-14 22:07:55 +0100798 PyThreadState *tstate;
799
800 if (!_PyGILState_check_enabled)
801 return 1;
802
803 if (autoTLSkey == -1)
804 return 1;
805
806 tstate = GET_TSTATE();
807 if (tstate == NULL)
808 return 0;
809
810 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700811}
812
Tim Peters19717fa2004-10-09 17:38:29 +0000813PyGILState_STATE
814PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000815{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 int current;
817 PyThreadState *tcur;
818 /* Note that we do not auto-init Python here - apart from
819 potential races with 2 threads auto-initializing, pep-311
820 spells out other issues. Embedders are expected to have
821 called Py_Initialize() and usually PyEval_InitThreads().
822 */
823 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
824 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
825 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100826 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
827 called from a new thread for the first time, we need the create the
828 GIL. */
829 PyEval_InitThreads();
830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000831 /* Create a new thread state for this thread */
832 tcur = PyThreadState_New(autoInterpreterState);
833 if (tcur == NULL)
834 Py_FatalError("Couldn't create thread-state for new thread");
835 /* This is our thread state! We'll need to delete it in the
836 matching call to PyGILState_Release(). */
837 tcur->gilstate_counter = 0;
838 current = 0; /* new thread state is never current */
839 }
840 else
841 current = PyThreadState_IsCurrent(tcur);
842 if (current == 0)
843 PyEval_RestoreThread(tcur);
844 /* Update our counter in the thread-state - no need for locks:
845 - tcur will remain valid as we hold the GIL.
846 - the counter is safe as we are the only thread "allowed"
847 to modify this value
848 */
849 ++tcur->gilstate_counter;
850 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000851}
852
Tim Peters19717fa2004-10-09 17:38:29 +0000853void
854PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
857 autoTLSkey);
858 if (tcur == NULL)
859 Py_FatalError("auto-releasing thread-state, "
860 "but no thread-state for this thread");
861 /* We must hold the GIL and have our thread state current */
862 /* XXX - remove the check - the assert should be fine,
863 but while this is very new (April 2003), the extra check
864 by release-only users can't hurt.
865 */
866 if (! PyThreadState_IsCurrent(tcur))
867 Py_FatalError("This thread state must be current when releasing");
868 assert(PyThreadState_IsCurrent(tcur));
869 --tcur->gilstate_counter;
870 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 /* If we're going to destroy this thread-state, we must
873 * clear it while the GIL is held, as destructors may run.
874 */
875 if (tcur->gilstate_counter == 0) {
876 /* can't have been locked when we created it */
877 assert(oldstate == PyGILState_UNLOCKED);
878 PyThreadState_Clear(tcur);
879 /* Delete the thread-state. Note this releases the GIL too!
880 * It's vital that the GIL be held here, to avoid shutdown
881 * races; see bugs 225673 and 1061968 (that nasty bug has a
882 * habit of coming back).
883 */
884 PyThreadState_DeleteCurrent();
885 }
886 /* Release the lock if necessary */
887 else if (oldstate == PyGILState_UNLOCKED)
888 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000889}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000890
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400891#endif /* WITH_THREAD */
892
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000893#ifdef __cplusplus
894}
895#endif
896
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000897