blob: 61bda2a9fbb08bf9f785818f34a95aadf09ce9bf [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;
Brett Cannon3cebf932016-09-05 15:33:46 -070094 interp->eval_frame = _PyEval_EvalFrameDefault;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000095#ifdef HAVE_DLOPEN
Serhiy Storchakac2f7d872016-05-04 09:44:44 +030096#if HAVE_DECL_RTLD_NOW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 interp->dlopenflags = RTLD_NOW;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000098#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 interp->dlopenflags = RTLD_LAZY;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000100#endif
101#endif
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000102#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 interp->tscdump = 0;
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000104#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +0000105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 HEAD_LOCK();
107 interp->next = interp_head;
108 interp_head = interp;
109 HEAD_UNLOCK();
110 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 return interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000113}
114
115
116void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000117PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000119 PyThreadState *p;
120 HEAD_LOCK();
121 for (p = interp->tstate_head; p != NULL; p = p->next)
122 PyThreadState_Clear(p);
123 HEAD_UNLOCK();
124 Py_CLEAR(interp->codec_search_path);
125 Py_CLEAR(interp->codec_search_cache);
126 Py_CLEAR(interp->codec_error_registry);
127 Py_CLEAR(interp->modules);
128 Py_CLEAR(interp->modules_by_index);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000129 Py_CLEAR(interp->sysdict);
130 Py_CLEAR(interp->builtins);
Serhiy Storchaka87a5c512014-02-10 18:21:34 +0200131 Py_CLEAR(interp->builtins_copy);
Brett Cannonfd074152012-04-14 14:10:13 -0400132 Py_CLEAR(interp->importlib);
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300133 Py_CLEAR(interp->import_func);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000134}
135
136
137static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000138zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 PyThreadState *p;
141 /* No need to lock the mutex here because this should only happen
142 when the threads are all really dead (XXX famous last words). */
143 while ((p = interp->tstate_head) != NULL) {
144 PyThreadState_Delete(p);
145 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000146}
147
148
149void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000150PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000151{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 PyInterpreterState **p;
153 zapthreads(interp);
154 HEAD_LOCK();
155 for (p = &interp_head; ; p = &(*p)->next) {
156 if (*p == NULL)
157 Py_FatalError(
158 "PyInterpreterState_Delete: invalid interp");
159 if (*p == interp)
160 break;
161 }
162 if (interp->tstate_head != NULL)
163 Py_FatalError("PyInterpreterState_Delete: remaining threads");
164 *p = interp->next;
165 HEAD_UNLOCK();
Victor Stinner1a7425f2013-07-07 16:25:15 +0200166 PyMem_RawFree(interp);
Antoine Pitrou8db076c2011-10-30 19:13:55 +0100167#ifdef WITH_THREAD
168 if (interp_head == NULL && head_mutex != NULL) {
169 PyThread_free_lock(head_mutex);
170 head_mutex = NULL;
171 }
172#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000173}
174
175
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000176/* Default implementation for _PyThreadState_GetFrame */
177static struct _frame *
178threadstate_getframe(PyThreadState *self)
179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 return self->frame;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000181}
182
Victor Stinner45b9be52010-03-03 23:28:07 +0000183static PyThreadState *
184new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000185{
Victor Stinner1a7425f2013-07-07 16:25:15 +0200186 PyThreadState *tstate = (PyThreadState *)PyMem_RawMalloc(sizeof(PyThreadState));
Tim Peters84705582004-10-10 02:47:33 +0000187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (_PyThreadState_GetFrame == NULL)
189 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000191 if (tstate != NULL) {
192 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000193
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000194 tstate->frame = NULL;
195 tstate->recursion_depth = 0;
196 tstate->overflowed = 0;
197 tstate->recursion_critical = 0;
198 tstate->tracing = 0;
199 tstate->use_tracing = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000200 tstate->gilstate_counter = 0;
201 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000202#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000203 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000204#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 tstate->thread_id = 0;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000206#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000208 tstate->dict = NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 tstate->curexc_type = NULL;
211 tstate->curexc_value = NULL;
212 tstate->curexc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 tstate->exc_type = NULL;
215 tstate->exc_value = NULL;
216 tstate->exc_traceback = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000217
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000218 tstate->c_profilefunc = NULL;
219 tstate->c_tracefunc = NULL;
220 tstate->c_profileobj = NULL;
221 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000222
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200223 tstate->trash_delete_nesting = 0;
224 tstate->trash_delete_later = NULL;
Antoine Pitrou7b476992013-09-07 23:38:37 +0200225 tstate->on_delete = NULL;
226 tstate->on_delete_data = NULL;
Antoine Pitrou2b0218a2012-09-06 00:59:49 +0200227
Yury Selivanov75445082015-05-11 22:57:16 -0400228 tstate->coroutine_wrapper = NULL;
Yury Selivanovaab3c4a2015-06-02 18:43:51 -0400229 tstate->in_coroutine_wrapper = 0;
Yury Selivanov75445082015-05-11 22:57:16 -0400230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 if (init)
232 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200235 tstate->prev = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 tstate->next = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200237 if (tstate->next)
238 tstate->next->prev = tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 interp->tstate_head = tstate;
240 HEAD_UNLOCK();
241 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000243 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000244}
245
Victor Stinner45b9be52010-03-03 23:28:07 +0000246PyThreadState *
247PyThreadState_New(PyInterpreterState *interp)
248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000249 return new_threadstate(interp, 1);
Victor Stinner45b9be52010-03-03 23:28:07 +0000250}
251
252PyThreadState *
253_PyThreadState_Prealloc(PyInterpreterState *interp)
254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 return new_threadstate(interp, 0);
Victor Stinner45b9be52010-03-03 23:28:07 +0000256}
257
258void
259_PyThreadState_Init(PyThreadState *tstate)
260{
261#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000262 _PyGILState_NoteThreadState(tstate);
Victor Stinner45b9be52010-03-03 23:28:07 +0000263#endif
264}
265
Martin v. Löwis1a214512008-06-11 05:26:20 +0000266PyObject*
Martin v. Löwis7800f752012-06-22 12:20:55 +0200267PyState_FindModule(struct PyModuleDef* module)
Martin v. Löwis1a214512008-06-11 05:26:20 +0000268{
Martin v. Löwis7800f752012-06-22 12:20:55 +0200269 Py_ssize_t index = module->m_base.m_index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100270 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 PyObject *res;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000272 if (module->m_slots) {
273 return NULL;
274 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 if (index == 0)
276 return NULL;
277 if (state->modules_by_index == NULL)
278 return NULL;
Antoine Pitrou75506e82012-08-20 19:30:46 +0200279 if (index >= PyList_GET_SIZE(state->modules_by_index))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return NULL;
281 res = PyList_GET_ITEM(state->modules_by_index, index);
282 return res==Py_None ? NULL : res;
Martin v. Löwis1a214512008-06-11 05:26:20 +0000283}
284
285int
286_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
287{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000288 PyInterpreterState *state;
Berker Peksag4b7b5652016-08-22 18:05:56 +0300289 if (!def) {
290 assert(PyErr_Occurred());
291 return -1;
292 }
Nick Coghland5cacbb2015-05-23 22:24:10 +1000293 if (def->m_slots) {
294 PyErr_SetString(PyExc_SystemError,
295 "PyState_AddModule called on module with slots");
296 return -1;
297 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100298 state = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (!state->modules_by_index) {
300 state->modules_by_index = PyList_New(0);
301 if (!state->modules_by_index)
302 return -1;
303 }
304 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
305 if (PyList_Append(state->modules_by_index, Py_None) < 0)
306 return -1;
307 Py_INCREF(module);
308 return PyList_SetItem(state->modules_by_index,
309 def->m_base.m_index, module);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000310}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000311
Martin v. Löwis7800f752012-06-22 12:20:55 +0200312int
313PyState_AddModule(PyObject* module, struct PyModuleDef* def)
314{
315 Py_ssize_t index;
Victor Stinnerb02ef712016-01-22 14:09:55 +0100316 PyInterpreterState *state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200317 if (!def) {
318 Py_FatalError("PyState_AddModule: Module Definition is NULL");
319 return -1;
320 }
321 index = def->m_base.m_index;
322 if (state->modules_by_index) {
323 if(PyList_GET_SIZE(state->modules_by_index) >= index) {
324 if(module == PyList_GET_ITEM(state->modules_by_index, index)) {
325 Py_FatalError("PyState_AddModule: Module already added!");
326 return -1;
327 }
328 }
329 }
330 return _PyState_AddModule(module, def);
331}
332
333int
334PyState_RemoveModule(struct PyModuleDef* def)
335{
Nick Coghland5cacbb2015-05-23 22:24:10 +1000336 PyInterpreterState *state;
Martin v. Löwis7800f752012-06-22 12:20:55 +0200337 Py_ssize_t index = def->m_base.m_index;
Nick Coghland5cacbb2015-05-23 22:24:10 +1000338 if (def->m_slots) {
339 PyErr_SetString(PyExc_SystemError,
340 "PyState_RemoveModule called on module with slots");
341 return -1;
342 }
Victor Stinnerb02ef712016-01-22 14:09:55 +0100343 state = GET_INTERP_STATE();
Martin v. Löwis7800f752012-06-22 12:20:55 +0200344 if (index == 0) {
345 Py_FatalError("PyState_RemoveModule: Module index invalid.");
346 return -1;
347 }
348 if (state->modules_by_index == NULL) {
349 Py_FatalError("PyState_RemoveModule: Interpreters module-list not acessible.");
350 return -1;
351 }
352 if (index > PyList_GET_SIZE(state->modules_by_index)) {
353 Py_FatalError("PyState_RemoveModule: Module index out of bounds.");
354 return -1;
355 }
356 return PyList_SetItem(state->modules_by_index, index, Py_None);
357}
358
Antoine Pitrou40322e62013-08-11 00:30:09 +0200359/* used by import.c:PyImport_Cleanup */
360void
361_PyState_ClearModules(void)
362{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100363 PyInterpreterState *state = GET_INTERP_STATE();
Antoine Pitrou40322e62013-08-11 00:30:09 +0200364 if (state->modules_by_index) {
365 Py_ssize_t i;
366 for (i = 0; i < PyList_GET_SIZE(state->modules_by_index); i++) {
367 PyObject *m = PyList_GET_ITEM(state->modules_by_index, i);
368 if (PyModule_Check(m)) {
369 /* cleanup the saved copy of module dicts */
370 PyModuleDef *md = PyModule_GetDef(m);
371 if (md)
372 Py_CLEAR(md->m_base.m_copy);
373 }
374 }
375 /* Setting modules_by_index to NULL could be dangerous, so we
376 clear the list instead. */
377 if (PyList_SetSlice(state->modules_by_index,
378 0, PyList_GET_SIZE(state->modules_by_index),
379 NULL))
380 PyErr_WriteUnraisable(state->modules_by_index);
381 }
382}
383
Guido van Rossuma027efa1997-05-05 20:56:21 +0000384void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000385PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 if (Py_VerboseFlag && tstate->frame != NULL)
388 fprintf(stderr,
389 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 Py_CLEAR(tstate->dict);
394 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 Py_CLEAR(tstate->curexc_type);
397 Py_CLEAR(tstate->curexc_value);
398 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 Py_CLEAR(tstate->exc_type);
401 Py_CLEAR(tstate->exc_value);
402 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 tstate->c_profilefunc = NULL;
405 tstate->c_tracefunc = NULL;
406 Py_CLEAR(tstate->c_profileobj);
407 Py_CLEAR(tstate->c_traceobj);
Yury Selivanov75445082015-05-11 22:57:16 -0400408
409 Py_CLEAR(tstate->coroutine_wrapper);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000410}
411
412
Guido van Rossum29757862001-01-23 01:46:06 +0000413/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
414static void
415tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyInterpreterState *interp;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000418 if (tstate == NULL)
419 Py_FatalError("PyThreadState_Delete: NULL tstate");
420 interp = tstate->interp;
421 if (interp == NULL)
422 Py_FatalError("PyThreadState_Delete: NULL interp");
423 HEAD_LOCK();
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200424 if (tstate->prev)
425 tstate->prev->next = tstate->next;
426 else
427 interp->tstate_head = tstate->next;
428 if (tstate->next)
429 tstate->next->prev = tstate->prev;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 HEAD_UNLOCK();
Antoine Pitrou7b476992013-09-07 23:38:37 +0200431 if (tstate->on_delete != NULL) {
432 tstate->on_delete(tstate->on_delete_data);
433 }
Victor Stinner1a7425f2013-07-07 16:25:15 +0200434 PyMem_RawFree(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000435}
436
437
Guido van Rossum29757862001-01-23 01:46:06 +0000438void
439PyThreadState_Delete(PyThreadState *tstate)
440{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100441 if (tstate == GET_TSTATE())
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 Py_FatalError("PyThreadState_Delete: tstate is still current");
Tim Petersf4e69282006-02-27 17:15:31 +0000443#ifdef WITH_THREAD
Antoine Pitrou079ce542010-09-08 12:37:10 +0000444 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 PyThread_delete_key_value(autoTLSkey);
Tim Petersf4e69282006-02-27 17:15:31 +0000446#endif /* WITH_THREAD */
Christian Heimesb9dbc7d2013-07-01 23:42:28 +0200447 tstate_delete_common(tstate);
Guido van Rossum29757862001-01-23 01:46:06 +0000448}
449
450
451#ifdef WITH_THREAD
452void
453PyThreadState_DeleteCurrent()
454{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100455 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (tstate == NULL)
457 Py_FatalError(
458 "PyThreadState_DeleteCurrent: no current tstate");
Victor Stinner8a1be612016-03-14 22:07:55 +0100459 tstate_delete_common(tstate);
Antoine Pitrou079ce542010-09-08 12:37:10 +0000460 if (autoInterpreterState && PyThread_get_key_value(autoTLSkey) == tstate)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyThread_delete_key_value(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100462 SET_TSTATE(NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PyEval_ReleaseLock();
Guido van Rossum29757862001-01-23 01:46:06 +0000464}
465#endif /* WITH_THREAD */
466
467
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200468/*
469 * Delete all thread states except the one passed as argument.
470 * Note that, if there is a current thread state, it *must* be the one
471 * passed as argument. Also, this won't touch any other interpreters
472 * than the current one, since we don't know which thread state should
473 * be kept in those other interpreteres.
474 */
475void
476_PyThreadState_DeleteExcept(PyThreadState *tstate)
477{
478 PyInterpreterState *interp = tstate->interp;
479 PyThreadState *p, *next, *garbage;
480 HEAD_LOCK();
481 /* Remove all thread states, except tstate, from the linked list of
482 thread states. This will allow calling PyThreadState_Clear()
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200483 without holding the lock. */
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200484 garbage = interp->tstate_head;
Charles-Francois Natalif28dfdd2013-05-08 21:09:52 +0200485 if (garbage == tstate)
486 garbage = tstate->next;
487 if (tstate->prev)
488 tstate->prev->next = tstate->next;
489 if (tstate->next)
490 tstate->next->prev = tstate->prev;
491 tstate->prev = tstate->next = NULL;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200492 interp->tstate_head = tstate;
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200493 HEAD_UNLOCK();
494 /* Clear and deallocate all stale thread states. Even if this
495 executes Python code, we should be safe since it executes
496 in the current thread, not one of the stale threads. */
497 for (p = garbage; p; p = next) {
498 next = p->next;
499 PyThreadState_Clear(p);
Victor Stinner1a7425f2013-07-07 16:25:15 +0200500 PyMem_RawFree(p);
Antoine Pitrou8408cea2013-05-05 23:47:09 +0200501 }
502}
503
504
Guido van Rossuma027efa1997-05-05 20:56:21 +0000505PyThreadState *
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100506_PyThreadState_UncheckedGet(void)
507{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100508 return GET_TSTATE();
Victor Stinnerbfd316e2016-01-20 11:12:38 +0100509}
510
511
512PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000513PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000514{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100515 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (tstate == NULL)
517 Py_FatalError("PyThreadState_Get: no current thread");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000520}
521
522
523PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000524PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000525{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100526 PyThreadState *oldts = GET_TSTATE();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000527
Victor Stinnerb02ef712016-01-22 14:09:55 +0100528 SET_TSTATE(newts);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 /* It should not be possible for more than one thread state
530 to be used for a thread. Check this the best we can in debug
531 builds.
532 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000533#if defined(Py_DEBUG) && defined(WITH_THREAD)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (newts) {
535 /* This can be called from PyEval_RestoreThread(). Similar
536 to it, we need to ensure errno doesn't change.
537 */
538 int err = errno;
539 PyThreadState *check = PyGILState_GetThisThreadState();
540 if (check && check->interp == newts->interp && check != newts)
541 Py_FatalError("Invalid thread state for this thread");
542 errno = err;
543 }
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000544#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000546}
Guido van Rossumede04391998-04-10 20:18:25 +0000547
548/* An extension mechanism to store arbitrary additional per-thread state.
549 PyThreadState_GetDict() returns a dictionary that can be used to hold such
550 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000551 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
552 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000553
554PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000555PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000556{
Victor Stinnerb02ef712016-01-22 14:09:55 +0100557 PyThreadState *tstate = GET_TSTATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 if (tstate == NULL)
559 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (tstate->dict == NULL) {
562 PyObject *d;
563 tstate->dict = d = PyDict_New();
564 if (d == NULL)
565 PyErr_Clear();
566 }
567 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000568}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000569
570
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000571/* Asynchronously raise an exception in a thread.
572 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000573 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000574 to call this, or use ctypes. Must be called with the GIL held.
575 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
576 match any known thread id). Can be called with exc=NULL to clear an
577 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000578
579int
580PyThreadState_SetAsyncExc(long id, PyObject *exc) {
Victor Stinnerb02ef712016-01-22 14:09:55 +0100581 PyInterpreterState *interp = GET_INTERP_STATE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000582 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 /* Although the GIL is held, a few C API functions can be called
585 * without the GIL held, and in particular some that create and
586 * destroy thread and interpreter states. Those can mutate the
587 * list of thread states we're traversing, so to prevent that we lock
588 * head_mutex for the duration.
589 */
590 HEAD_LOCK();
591 for (p = interp->tstate_head; p != NULL; p = p->next) {
592 if (p->thread_id == id) {
593 /* Tricky: we need to decref the current value
594 * (if any) in p->async_exc, but that can in turn
595 * allow arbitrary Python code to run, including
596 * perhaps calls to this function. To prevent
597 * deadlock, we need to release head_mutex before
598 * the decref.
599 */
600 PyObject *old_exc = p->async_exc;
601 Py_XINCREF(exc);
602 p->async_exc = exc;
603 HEAD_UNLOCK();
604 Py_XDECREF(old_exc);
605 _PyEval_SignalAsyncExc();
606 return 1;
607 }
608 }
609 HEAD_UNLOCK();
610 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000611}
612
613
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000614/* Routines for advanced debuggers, requested by David Beazley.
615 Don't use unless you know what you are doing! */
616
617PyInterpreterState *
618PyInterpreterState_Head(void)
619{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000620 return interp_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000621}
622
623PyInterpreterState *
624PyInterpreterState_Next(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 return interp->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000626}
627
628PyThreadState *
629PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return interp->tstate_head;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000631}
632
633PyThreadState *
634PyThreadState_Next(PyThreadState *tstate) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return tstate->next;
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000636}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000637
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000638/* The implementation of sys._current_frames(). This is intended to be
639 called with the GIL held, as it will be when called via
640 sys._current_frames(). It's possible it would work fine even without
641 the GIL held, but haven't thought enough about that.
642*/
643PyObject *
644_PyThread_CurrentFrames(void)
645{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *result;
647 PyInterpreterState *i;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000648
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 result = PyDict_New();
650 if (result == NULL)
651 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* for i in all interpreters:
654 * for t in all of i's thread states:
655 * if t's frame isn't NULL, map t's id to its frame
Ezio Melotti13925002011-03-16 11:05:33 +0200656 * Because these lists can mutate even when the GIL is held, we
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000657 * need to grab head_mutex for the duration.
658 */
659 HEAD_LOCK();
660 for (i = interp_head; i != NULL; i = i->next) {
661 PyThreadState *t;
662 for (t = i->tstate_head; t != NULL; t = t->next) {
663 PyObject *id;
664 int stat;
665 struct _frame *frame = t->frame;
666 if (frame == NULL)
667 continue;
668 id = PyLong_FromLong(t->thread_id);
669 if (id == NULL)
670 goto Fail;
671 stat = PyDict_SetItem(result, id, (PyObject *)frame);
672 Py_DECREF(id);
673 if (stat < 0)
674 goto Fail;
675 }
676 }
677 HEAD_UNLOCK();
678 return result;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000679
680 Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 HEAD_UNLOCK();
682 Py_DECREF(result);
683 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000684}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000685
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000686/* Python "auto thread state" API. */
687#ifdef WITH_THREAD
688
689/* Keep this as a static, as it is not reliable! It can only
690 ever be compared to the state for the *current* thread.
691 * If not equal, then it doesn't matter that the actual
692 value may change immediately after comparison, as it can't
693 possibly change to the current thread's state.
694 * If equal, then the current thread holds the lock, so the value can't
695 change until we yield the lock.
696*/
697static int
698PyThreadState_IsCurrent(PyThreadState *tstate)
699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 /* Must be the tstate for this thread */
701 assert(PyGILState_GetThisThreadState()==tstate);
Victor Stinnerb02ef712016-01-22 14:09:55 +0100702 return tstate == GET_TSTATE();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000703}
704
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000705/* Internal initialization/finalization functions called by
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000706 Py_Initialize/Py_FinalizeEx
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000707*/
Tim Peters19717fa2004-10-09 17:38:29 +0000708void
709_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 assert(i && t); /* must init with valid states */
712 autoTLSkey = PyThread_create_key();
Kristján Valur Jónsson2fea9b92010-09-20 02:11:49 +0000713 if (autoTLSkey == -1)
714 Py_FatalError("Could not allocate TLS entry");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 autoInterpreterState = i;
716 assert(PyThread_get_key_value(autoTLSkey) == NULL);
717 assert(t->gilstate_counter == 0);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000720}
721
Victor Stinner861d9ab2016-03-16 22:45:24 +0100722PyInterpreterState *
723_PyGILState_GetInterpreterStateUnsafe(void)
724{
725 return autoInterpreterState;
726}
727
Tim Peters19717fa2004-10-09 17:38:29 +0000728void
729_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 PyThread_delete_key(autoTLSkey);
Victor Stinner8a1be612016-03-14 22:07:55 +0100732 autoTLSkey = -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000734}
735
Charles-François Natalia233df82011-11-22 19:49:51 +0100736/* Reset the TLS key - called by PyOS_AfterFork().
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200737 * This should not be necessary, but some - buggy - pthread implementations
Charles-François Natalia233df82011-11-22 19:49:51 +0100738 * don't reset TLS upon fork(), see issue #10517.
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200739 */
740void
741_PyGILState_Reinit(void)
742{
743 PyThreadState *tstate = PyGILState_GetThisThreadState();
744 PyThread_delete_key(autoTLSkey);
745 if ((autoTLSkey = PyThread_create_key()) == -1)
746 Py_FatalError("Could not allocate TLS entry");
747
Charles-François Natalia233df82011-11-22 19:49:51 +0100748 /* If the thread had an associated auto thread state, reassociate it with
749 * the new key. */
750 if (tstate && PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
Antoine Pitrou0c759fe2011-04-27 19:28:05 +0200751 Py_FatalError("Couldn't create autoTLSkey mapping");
752}
753
Michael W. Hudson188d4362005-06-20 16:52:57 +0000754/* When a thread state is created for a thread by some mechanism other than
755 PyGILState_Ensure, it's important that the GILState machinery knows about
756 it so it doesn't try to create another thread state for the thread (this is
757 a better fix for SF bug #1010677 than the first one attempted).
758*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000759static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000760_PyGILState_NoteThreadState(PyThreadState* tstate)
761{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000762 /* If autoTLSkey isn't initialized, this must be the very first
763 threadstate created in Py_Initialize(). Don't do anything for now
764 (we'll be back here when _PyGILState_Init is called). */
765 if (!autoInterpreterState)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 /* Stick the thread state for this thread in thread local storage.
Michael W. Hudson188d4362005-06-20 16:52:57 +0000769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 The only situation where you can legitimately have more than one
771 thread state for an OS level thread is when there are multiple
Victor Stinner590cebe2013-12-13 11:08:56 +0100772 interpreters.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000773
Victor Stinner590cebe2013-12-13 11:08:56 +0100774 You shouldn't really be using the PyGILState_ APIs anyway (see issues
775 #10915 and #15751).
Michael W. Hudson188d4362005-06-20 16:52:57 +0000776
Victor Stinner590cebe2013-12-13 11:08:56 +0100777 The first thread state created for that given OS level thread will
778 "win", which seems reasonable behaviour.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 */
Victor Stinner590cebe2013-12-13 11:08:56 +0100780 if (PyThread_get_key_value(autoTLSkey) == NULL) {
781 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
782 Py_FatalError("Couldn't create autoTLSkey mapping");
783 }
Michael W. Hudson188d4362005-06-20 16:52:57 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 /* PyGILState_Release must not try to delete this thread state. */
786 tstate->gilstate_counter = 1;
Michael W. Hudson188d4362005-06-20 16:52:57 +0000787}
788
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000789/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000790PyThreadState *
791PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000792{
Antoine Pitrou079ce542010-09-08 12:37:10 +0000793 if (autoInterpreterState == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 return NULL;
795 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000796}
797
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700798int
799PyGILState_Check(void)
800{
Victor Stinner8a1be612016-03-14 22:07:55 +0100801 PyThreadState *tstate;
802
803 if (!_PyGILState_check_enabled)
804 return 1;
805
806 if (autoTLSkey == -1)
807 return 1;
808
809 tstate = GET_TSTATE();
810 if (tstate == NULL)
811 return 0;
812
813 return (tstate == PyGILState_GetThisThreadState());
Kristján Valur Jónsson684cd0e2013-03-23 03:36:16 -0700814}
815
Tim Peters19717fa2004-10-09 17:38:29 +0000816PyGILState_STATE
817PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 int current;
820 PyThreadState *tcur;
821 /* Note that we do not auto-init Python here - apart from
822 potential races with 2 threads auto-initializing, pep-311
823 spells out other issues. Embedders are expected to have
824 called Py_Initialize() and usually PyEval_InitThreads().
825 */
826 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
827 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
828 if (tcur == NULL) {
Victor Stinner62ca1002013-12-13 01:46:43 +0100829 /* At startup, Python has no concrete GIL. If PyGILState_Ensure() is
830 called from a new thread for the first time, we need the create the
831 GIL. */
832 PyEval_InitThreads();
833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 /* Create a new thread state for this thread */
835 tcur = PyThreadState_New(autoInterpreterState);
836 if (tcur == NULL)
837 Py_FatalError("Couldn't create thread-state for new thread");
838 /* This is our thread state! We'll need to delete it in the
839 matching call to PyGILState_Release(). */
840 tcur->gilstate_counter = 0;
841 current = 0; /* new thread state is never current */
842 }
843 else
844 current = PyThreadState_IsCurrent(tcur);
845 if (current == 0)
846 PyEval_RestoreThread(tcur);
847 /* Update our counter in the thread-state - no need for locks:
848 - tcur will remain valid as we hold the GIL.
849 - the counter is safe as we are the only thread "allowed"
850 to modify this value
851 */
852 ++tcur->gilstate_counter;
853 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000854}
855
Tim Peters19717fa2004-10-09 17:38:29 +0000856void
857PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
860 autoTLSkey);
861 if (tcur == NULL)
862 Py_FatalError("auto-releasing thread-state, "
863 "but no thread-state for this thread");
864 /* We must hold the GIL and have our thread state current */
865 /* XXX - remove the check - the assert should be fine,
866 but while this is very new (April 2003), the extra check
867 by release-only users can't hurt.
868 */
869 if (! PyThreadState_IsCurrent(tcur))
870 Py_FatalError("This thread state must be current when releasing");
871 assert(PyThreadState_IsCurrent(tcur));
872 --tcur->gilstate_counter;
873 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000874
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 /* If we're going to destroy this thread-state, we must
876 * clear it while the GIL is held, as destructors may run.
877 */
878 if (tcur->gilstate_counter == 0) {
879 /* can't have been locked when we created it */
880 assert(oldstate == PyGILState_UNLOCKED);
881 PyThreadState_Clear(tcur);
882 /* Delete the thread-state. Note this releases the GIL too!
883 * It's vital that the GIL be held here, to avoid shutdown
884 * races; see bugs 225673 and 1061968 (that nasty bug has a
885 * habit of coming back).
886 */
887 PyThreadState_DeleteCurrent();
888 }
889 /* Release the lock if necessary */
890 else if (oldstate == PyGILState_UNLOCKED)
891 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000892}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000893
Benjamin Peterson3bf01752012-04-13 18:06:36 -0400894#endif /* WITH_THREAD */
895
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000896#ifdef __cplusplus
897}
898#endif
899
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000900