blob: 7154aeac243a3e8208742faff4a6f60dc320600a [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
Tim Peters84705582004-10-10 02:47:33 +00006/* --------------------------------------------------------------------------
7CAUTION
8
9Always use malloc() and free() directly in this file. A number of these
10functions are advertised as safe to call when the GIL isn't held, and in
11a debug build Python redirects (e.g.) PyMem_NEW (etc) to Python's debugging
12obmalloc functions. Those aren't thread-safe (they rely on the GIL to avoid
13the expense of doing their own locking).
14-------------------------------------------------------------------------- */
15
Martin v. Löwisf0473d52001-07-18 16:17:16 +000016#ifdef HAVE_DLOPEN
17#ifdef HAVE_DLFCN_H
18#include <dlfcn.h>
19#endif
20#ifndef RTLD_LAZY
21#define RTLD_LAZY 1
22#endif
23#endif
24
25
Guido van Rossum1d5ad901999-06-18 14:22:24 +000026#ifdef WITH_THREAD
27#include "pythread.h"
28static PyThread_type_lock head_mutex = NULL; /* Protects interp->tstate_head */
Moshe Zadka9fb6af92000-08-04 21:27:47 +000029#define HEAD_INIT() (void)(head_mutex || (head_mutex = PyThread_allocate_lock()))
Guido van Rossum1d5ad901999-06-18 14:22:24 +000030#define HEAD_LOCK() PyThread_acquire_lock(head_mutex, WAIT_LOCK)
31#define HEAD_UNLOCK() PyThread_release_lock(head_mutex)
Michael W. Hudson188d4362005-06-20 16:52:57 +000032
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000033#ifdef __cplusplus
34extern "C" {
35#endif
36
Michael W. Hudson188d4362005-06-20 16:52:57 +000037/* The single PyInterpreterState used by this process'
38 GILState implementation
39*/
40static PyInterpreterState *autoInterpreterState = NULL;
41static int autoTLSkey = 0;
Guido van Rossum1d5ad901999-06-18 14:22:24 +000042#else
43#define HEAD_INIT() /* Nothing */
44#define HEAD_LOCK() /* Nothing */
45#define HEAD_UNLOCK() /* Nothing */
46#endif
47
Guido van Rossum25ce5661997-08-02 03:10:38 +000048static PyInterpreterState *interp_head = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000049
Jeffrey Yasskin39370832010-05-03 19:29:34 +000050/* Assuming the current thread holds the GIL, this is the
51 PyThreadState for the current thread. */
52_Py_atomic_address _PyThreadState_Current = {NULL};
Guido van Rossum6297a7a2003-02-19 15:53:17 +000053PyThreadFrameGetter _PyThreadState_GetFrame = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000054
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000055#ifdef WITH_THREAD
Michael W. Hudson188d4362005-06-20 16:52:57 +000056static void _PyGILState_NoteThreadState(PyThreadState* tstate);
Michael W. Hudsonce7da6c2005-09-30 08:20:24 +000057#endif
Michael W. Hudson188d4362005-06-20 16:52:57 +000058
Guido van Rossuma027efa1997-05-05 20:56:21 +000059
60PyInterpreterState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000061PyInterpreterState_New(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +000062{
Tim Peters84705582004-10-10 02:47:33 +000063 PyInterpreterState *interp = (PyInterpreterState *)
64 malloc(sizeof(PyInterpreterState));
Guido van Rossum25ce5661997-08-02 03:10:38 +000065
Guido van Rossuma027efa1997-05-05 20:56:21 +000066 if (interp != NULL) {
Guido van Rossum1d5ad901999-06-18 14:22:24 +000067 HEAD_INIT();
Thomas Wouters0e3f5912006-08-11 14:57:12 +000068#ifdef WITH_THREAD
69 if (head_mutex == NULL)
70 Py_FatalError("Can't initialize threads for interpreter");
71#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +000072 interp->modules = NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +000073 interp->modules_reloading = NULL;
Martin v. Löwis1a214512008-06-11 05:26:20 +000074 interp->modules_by_index = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +000075 interp->sysdict = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +000076 interp->builtins = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +000077 interp->tstate_head = NULL;
Gustavo Niemeyer5ddd4c32003-03-19 00:35:36 +000078 interp->codec_search_path = NULL;
79 interp->codec_search_cache = NULL;
80 interp->codec_error_registry = NULL;
Christian Heimes6a27efa2008-10-30 21:48:26 +000081 interp->codecs_initialized = 0;
Martin v. Löwisf0473d52001-07-18 16:17:16 +000082#ifdef HAVE_DLOPEN
83#ifdef RTLD_NOW
84 interp->dlopenflags = RTLD_NOW;
85#else
86 interp->dlopenflags = RTLD_LAZY;
87#endif
88#endif
Martin v. Löwisf30d60e2004-06-08 08:17:44 +000089#ifdef WITH_TSC
90 interp->tscdump = 0;
91#endif
Guido van Rossum25ce5661997-08-02 03:10:38 +000092
Tim Peters412f2462000-09-02 09:16:15 +000093 HEAD_LOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +000094 interp->next = interp_head;
95 interp_head = interp;
Tim Peters412f2462000-09-02 09:16:15 +000096 HEAD_UNLOCK();
Guido van Rossuma027efa1997-05-05 20:56:21 +000097 }
Guido van Rossum25ce5661997-08-02 03:10:38 +000098
Guido van Rossuma027efa1997-05-05 20:56:21 +000099 return interp;
100}
101
102
103void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000104PyInterpreterState_Clear(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000105{
106 PyThreadState *p;
Guido van Rossum1d5ad901999-06-18 14:22:24 +0000107 HEAD_LOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000108 for (p = interp->tstate_head; p != NULL; p = p->next)
109 PyThreadState_Clear(p);
Guido van Rossum1d5ad901999-06-18 14:22:24 +0000110 HEAD_UNLOCK();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000111 Py_CLEAR(interp->codec_search_path);
112 Py_CLEAR(interp->codec_search_cache);
113 Py_CLEAR(interp->codec_error_registry);
114 Py_CLEAR(interp->modules);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000115 Py_CLEAR(interp->modules_by_index);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000116 Py_CLEAR(interp->modules_reloading);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000117 Py_CLEAR(interp->sysdict);
118 Py_CLEAR(interp->builtins);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000119}
120
121
122static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000123zapthreads(PyInterpreterState *interp)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000124{
Guido van Rossum1d5ad901999-06-18 14:22:24 +0000125 PyThreadState *p;
126 /* No need to lock the mutex here because this should only happen
127 when the threads are all really dead (XXX famous last words). */
128 while ((p = interp->tstate_head) != NULL) {
Guido van Rossum25ce5661997-08-02 03:10:38 +0000129 PyThreadState_Delete(p);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000130 }
131}
132
133
134void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000135PyInterpreterState_Delete(PyInterpreterState *interp)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000136{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000137 PyInterpreterState **p;
138 zapthreads(interp);
Tim Peters412f2462000-09-02 09:16:15 +0000139 HEAD_LOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000140 for (p = &interp_head; ; p = &(*p)->next) {
141 if (*p == NULL)
142 Py_FatalError(
143 "PyInterpreterState_Delete: invalid interp");
144 if (*p == interp)
145 break;
146 }
147 if (interp->tstate_head != NULL)
148 Py_FatalError("PyInterpreterState_Delete: remaining threads");
149 *p = interp->next;
Tim Peters412f2462000-09-02 09:16:15 +0000150 HEAD_UNLOCK();
Tim Peters84705582004-10-10 02:47:33 +0000151 free(interp);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000152}
153
154
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000155/* Default implementation for _PyThreadState_GetFrame */
156static struct _frame *
157threadstate_getframe(PyThreadState *self)
158{
159 return self->frame;
160}
161
Victor Stinner45b9be52010-03-03 23:28:07 +0000162static PyThreadState *
163new_threadstate(PyInterpreterState *interp, int init)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000164{
Tim Peters84705582004-10-10 02:47:33 +0000165 PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState));
166
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000167 if (_PyThreadState_GetFrame == NULL)
Guido van Rossum6297a7a2003-02-19 15:53:17 +0000168 _PyThreadState_GetFrame = threadstate_getframe;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000169
Guido van Rossuma027efa1997-05-05 20:56:21 +0000170 if (tstate != NULL) {
Guido van Rossum25ce5661997-08-02 03:10:38 +0000171 tstate->interp = interp;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000172
173 tstate->frame = NULL;
174 tstate->recursion_depth = 0;
Martin v. Löwis5b222132007-06-10 09:51:05 +0000175 tstate->overflowed = 0;
176 tstate->recursion_critical = 0;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000177 tstate->tracing = 0;
Fred Drake9e3ad782001-07-03 23:39:52 +0000178 tstate->use_tracing = 0;
Michael W. Hudson019a78e2002-11-08 12:53:11 +0000179 tstate->tick_counter = 0;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000180 tstate->gilstate_counter = 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000181 tstate->async_exc = NULL;
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000182#ifdef WITH_THREAD
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000183 tstate->thread_id = PyThread_get_thread_ident();
Martin v. Löwisf9ce67d2003-07-13 10:41:53 +0000184#else
185 tstate->thread_id = 0;
186#endif
Guido van Rossuma027efa1997-05-05 20:56:21 +0000187
Guido van Rossumede04391998-04-10 20:18:25 +0000188 tstate->dict = NULL;
189
Guido van Rossuma027efa1997-05-05 20:56:21 +0000190 tstate->curexc_type = NULL;
191 tstate->curexc_value = NULL;
192 tstate->curexc_traceback = NULL;
193
194 tstate->exc_type = NULL;
195 tstate->exc_value = NULL;
196 tstate->exc_traceback = NULL;
197
Fred Drake5755ce62001-06-27 19:19:46 +0000198 tstate->c_profilefunc = NULL;
199 tstate->c_tracefunc = NULL;
200 tstate->c_profileobj = NULL;
201 tstate->c_traceobj = NULL;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000202
Victor Stinner45b9be52010-03-03 23:28:07 +0000203 if (init)
204 _PyThreadState_Init(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000205
Guido van Rossum1d5ad901999-06-18 14:22:24 +0000206 HEAD_LOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000207 tstate->next = interp->tstate_head;
208 interp->tstate_head = tstate;
Guido van Rossum1d5ad901999-06-18 14:22:24 +0000209 HEAD_UNLOCK();
Guido van Rossuma027efa1997-05-05 20:56:21 +0000210 }
Guido van Rossum25ce5661997-08-02 03:10:38 +0000211
Guido van Rossuma027efa1997-05-05 20:56:21 +0000212 return tstate;
213}
214
Victor Stinner45b9be52010-03-03 23:28:07 +0000215PyThreadState *
216PyThreadState_New(PyInterpreterState *interp)
217{
218 return new_threadstate(interp, 1);
219}
220
221PyThreadState *
222_PyThreadState_Prealloc(PyInterpreterState *interp)
223{
224 return new_threadstate(interp, 0);
225}
226
227void
228_PyThreadState_Init(PyThreadState *tstate)
229{
230#ifdef WITH_THREAD
231 _PyGILState_NoteThreadState(tstate);
232#endif
233}
234
Martin v. Löwis1a214512008-06-11 05:26:20 +0000235PyObject*
236PyState_FindModule(struct PyModuleDef* m)
237{
238 Py_ssize_t index = m->m_base.m_index;
239 PyInterpreterState *state = PyThreadState_GET()->interp;
240 PyObject *res;
241 if (index == 0)
242 return NULL;
243 if (state->modules_by_index == NULL)
244 return NULL;
245 if (index > PyList_GET_SIZE(state->modules_by_index))
246 return NULL;
247 res = PyList_GET_ITEM(state->modules_by_index, index);
248 return res==Py_None ? NULL : res;
249}
250
251int
252_PyState_AddModule(PyObject* module, struct PyModuleDef* def)
253{
254 PyInterpreterState *state = PyThreadState_GET()->interp;
255 if (!def)
256 return -1;
257 if (!state->modules_by_index) {
Martin v. Löwis276c3712008-11-17 16:22:11 +0000258 state->modules_by_index = PyList_New(0);
Martin v. Löwis1a214512008-06-11 05:26:20 +0000259 if (!state->modules_by_index)
260 return -1;
261 }
262 while(PyList_GET_SIZE(state->modules_by_index) <= def->m_base.m_index)
263 if (PyList_Append(state->modules_by_index, Py_None) < 0)
264 return -1;
265 Py_INCREF(module);
266 return PyList_SetItem(state->modules_by_index,
267 def->m_base.m_index, module);
268}
Guido van Rossuma027efa1997-05-05 20:56:21 +0000269
270void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000271PyThreadState_Clear(PyThreadState *tstate)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000272{
Guido van Rossum22348dc1997-11-03 22:08:36 +0000273 if (Py_VerboseFlag && tstate->frame != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000274 fprintf(stderr,
Guido van Rossum5f896a41997-08-21 02:28:19 +0000275 "PyThreadState_Clear: warning: thread still has a frame\n");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000276
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000277 Py_CLEAR(tstate->frame);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000279 Py_CLEAR(tstate->dict);
280 Py_CLEAR(tstate->async_exc);
Guido van Rossumede04391998-04-10 20:18:25 +0000281
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000282 Py_CLEAR(tstate->curexc_type);
283 Py_CLEAR(tstate->curexc_value);
284 Py_CLEAR(tstate->curexc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000285
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000286 Py_CLEAR(tstate->exc_type);
287 Py_CLEAR(tstate->exc_value);
288 Py_CLEAR(tstate->exc_traceback);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000289
Fred Drake5755ce62001-06-27 19:19:46 +0000290 tstate->c_profilefunc = NULL;
291 tstate->c_tracefunc = NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000292 Py_CLEAR(tstate->c_profileobj);
293 Py_CLEAR(tstate->c_traceobj);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000294}
295
296
Guido van Rossum29757862001-01-23 01:46:06 +0000297/* Common code for PyThreadState_Delete() and PyThreadState_DeleteCurrent() */
298static void
299tstate_delete_common(PyThreadState *tstate)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000300{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000301 PyInterpreterState *interp;
302 PyThreadState **p;
Christian Heimese1c98112008-01-21 11:20:28 +0000303 PyThreadState *prev_p = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000304 if (tstate == NULL)
305 Py_FatalError("PyThreadState_Delete: NULL tstate");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000306 interp = tstate->interp;
307 if (interp == NULL)
308 Py_FatalError("PyThreadState_Delete: NULL interp");
Guido van Rossum1d5ad901999-06-18 14:22:24 +0000309 HEAD_LOCK();
Guido van Rossum25ce5661997-08-02 03:10:38 +0000310 for (p = &interp->tstate_head; ; p = &(*p)->next) {
311 if (*p == NULL)
312 Py_FatalError(
313 "PyThreadState_Delete: invalid tstate");
314 if (*p == tstate)
315 break;
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000316 /* Sanity check. These states should never happen but if
317 * they do we must abort. Otherwise we'll end up spinning in
318 * in a tight loop with the lock held. A similar check is done
319 * in thread.c find_key(). */
Christian Heimese1c98112008-01-21 11:20:28 +0000320 if (*p == prev_p)
321 Py_FatalError(
322 "PyThreadState_Delete: small circular list(!)"
323 " and tstate not found.");
324 prev_p = *p;
325 if ((*p)->next == interp->tstate_head)
326 Py_FatalError(
327 "PyThreadState_Delete: circular list(!) and"
328 " tstate not found.");
Guido van Rossum25ce5661997-08-02 03:10:38 +0000329 }
330 *p = tstate->next;
Guido van Rossum1d5ad901999-06-18 14:22:24 +0000331 HEAD_UNLOCK();
Tim Peters84705582004-10-10 02:47:33 +0000332 free(tstate);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000333}
334
335
Guido van Rossum29757862001-01-23 01:46:06 +0000336void
337PyThreadState_Delete(PyThreadState *tstate)
338{
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000339 if (tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current))
Guido van Rossum29757862001-01-23 01:46:06 +0000340 Py_FatalError("PyThreadState_Delete: tstate is still current");
341 tstate_delete_common(tstate);
Tim Petersf4e69282006-02-27 17:15:31 +0000342#ifdef WITH_THREAD
343 if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate)
344 PyThread_delete_key_value(autoTLSkey);
345#endif /* WITH_THREAD */
Guido van Rossum29757862001-01-23 01:46:06 +0000346}
347
348
349#ifdef WITH_THREAD
350void
351PyThreadState_DeleteCurrent()
352{
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000353 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
354 &_PyThreadState_Current);
Guido van Rossum29757862001-01-23 01:46:06 +0000355 if (tstate == NULL)
356 Py_FatalError(
357 "PyThreadState_DeleteCurrent: no current tstate");
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000358 _Py_atomic_store_relaxed(&_PyThreadState_Current, NULL);
Guido van Rossum29757862001-01-23 01:46:06 +0000359 tstate_delete_common(tstate);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000360 if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate)
361 PyThread_delete_key_value(autoTLSkey);
Guido van Rossum29757862001-01-23 01:46:06 +0000362 PyEval_ReleaseLock();
363}
364#endif /* WITH_THREAD */
365
366
Guido van Rossuma027efa1997-05-05 20:56:21 +0000367PyThreadState *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000368PyThreadState_Get(void)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000369{
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000370 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
371 &_PyThreadState_Current);
372 if (tstate == NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000373 Py_FatalError("PyThreadState_Get: no current thread");
374
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000375 return tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000376}
377
378
379PyThreadState *
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000380PyThreadState_Swap(PyThreadState *newts)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000381{
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000382 PyThreadState *oldts = (PyThreadState*)_Py_atomic_load_relaxed(
383 &_PyThreadState_Current);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000384
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000385 _Py_atomic_store_relaxed(&_PyThreadState_Current, newts);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000386 /* It should not be possible for more than one thread state
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000387 to be used for a thread. Check this the best we can in debug
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000388 builds.
389 */
Martin v. Löwis9e296252003-05-01 05:25:29 +0000390#if defined(Py_DEBUG) && defined(WITH_THREAD)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000391 if (newts) {
Thomas Wouters89f507f2006-12-13 04:49:30 +0000392 /* This can be called from PyEval_RestoreThread(). Similar
393 to it, we need to ensure errno doesn't change.
394 */
395 int err = errno;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000396 PyThreadState *check = PyGILState_GetThisThreadState();
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000397 if (check && check->interp == newts->interp && check != newts)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000398 Py_FatalError("Invalid thread state for this thread");
Thomas Wouters89f507f2006-12-13 04:49:30 +0000399 errno = err;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000400 }
401#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000402 return oldts;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000403}
Guido van Rossumede04391998-04-10 20:18:25 +0000404
405/* An extension mechanism to store arbitrary additional per-thread state.
406 PyThreadState_GetDict() returns a dictionary that can be used to hold such
407 state; the caller should pick a unique key and store its state there. If
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000408 PyThreadState_GetDict() returns NULL, an exception has *not* been raised
409 and the caller should assume no per-thread state is available. */
Guido van Rossumede04391998-04-10 20:18:25 +0000410
411PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000412PyThreadState_GetDict(void)
Guido van Rossumede04391998-04-10 20:18:25 +0000413{
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000414 PyThreadState *tstate = (PyThreadState*)_Py_atomic_load_relaxed(
415 &_PyThreadState_Current);
416 if (tstate == NULL)
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000417 return NULL;
Guido van Rossumede04391998-04-10 20:18:25 +0000418
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000419 if (tstate->dict == NULL) {
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000420 PyObject *d;
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000421 tstate->dict = d = PyDict_New();
Guido van Rossum0fc8f002003-04-15 15:12:39 +0000422 if (d == NULL)
423 PyErr_Clear();
424 }
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000425 return tstate->dict;
Guido van Rossumede04391998-04-10 20:18:25 +0000426}
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000427
428
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000429/* Asynchronously raise an exception in a thread.
430 Requested by Just van Rossum and Alex Martelli.
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000431 To prevent naive misuse, you must write your own extension
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000432 to call this, or use ctypes. Must be called with the GIL held.
433 Returns the number of tstates modified (normally 1, but 0 if `id` didn't
434 match any known thread id). Can be called with exc=NULL to clear an
435 existing async exception. This raises no exceptions. */
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000436
437int
438PyThreadState_SetAsyncExc(long id, PyObject *exc) {
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000439 PyThreadState *tstate = PyThreadState_GET();
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000440 PyInterpreterState *interp = tstate->interp;
441 PyThreadState *p;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000442
443 /* Although the GIL is held, a few C API functions can be called
444 * without the GIL held, and in particular some that create and
445 * destroy thread and interpreter states. Those can mutate the
446 * list of thread states we're traversing, so to prevent that we lock
447 * head_mutex for the duration.
448 */
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000449 HEAD_LOCK();
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000450 for (p = interp->tstate_head; p != NULL; p = p->next) {
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000451 if (p->thread_id == id) {
452 /* Tricky: we need to decref the current value
453 * (if any) in p->async_exc, but that can in turn
454 * allow arbitrary Python code to run, including
455 * perhaps calls to this function. To prevent
456 * deadlock, we need to release head_mutex before
457 * the decref.
458 */
459 PyObject *old_exc = p->async_exc;
460 Py_XINCREF(exc);
461 p->async_exc = exc;
462 HEAD_UNLOCK();
463 Py_XDECREF(old_exc);
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000464 _PyEval_SignalAsyncExc();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000465 return 1;
466 }
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000467 }
Guido van Rossum0f1f63c2005-02-08 02:07:57 +0000468 HEAD_UNLOCK();
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000469 return 0;
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000470}
471
472
Guido van Rossumf5df46d2001-07-19 12:19:27 +0000473/* Routines for advanced debuggers, requested by David Beazley.
474 Don't use unless you know what you are doing! */
475
476PyInterpreterState *
477PyInterpreterState_Head(void)
478{
479 return interp_head;
480}
481
482PyInterpreterState *
483PyInterpreterState_Next(PyInterpreterState *interp) {
484 return interp->next;
485}
486
487PyThreadState *
488PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
489 return interp->tstate_head;
490}
491
492PyThreadState *
493PyThreadState_Next(PyThreadState *tstate) {
494 return tstate->next;
495}
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000496
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000497/* The implementation of sys._current_frames(). This is intended to be
498 called with the GIL held, as it will be when called via
499 sys._current_frames(). It's possible it would work fine even without
500 the GIL held, but haven't thought enough about that.
501*/
502PyObject *
503_PyThread_CurrentFrames(void)
504{
505 PyObject *result;
506 PyInterpreterState *i;
507
508 result = PyDict_New();
509 if (result == NULL)
510 return NULL;
511
512 /* for i in all interpreters:
513 * for t in all of i's thread states:
514 * if t's frame isn't NULL, map t's id to its frame
515 * Because these lists can mutute even when the GIL is held, we
516 * need to grab head_mutex for the duration.
517 */
518 HEAD_LOCK();
519 for (i = interp_head; i != NULL; i = i->next) {
520 PyThreadState *t;
521 for (t = i->tstate_head; t != NULL; t = t->next) {
522 PyObject *id;
523 int stat;
524 struct _frame *frame = t->frame;
525 if (frame == NULL)
526 continue;
Christian Heimes217cfd12007-12-02 14:31:20 +0000527 id = PyLong_FromLong(t->thread_id);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000528 if (id == NULL)
529 goto Fail;
530 stat = PyDict_SetItem(result, id, (PyObject *)frame);
531 Py_DECREF(id);
532 if (stat < 0)
533 goto Fail;
534 }
535 }
536 HEAD_UNLOCK();
537 return result;
538
539 Fail:
540 HEAD_UNLOCK();
541 Py_DECREF(result);
542 return NULL;
543}
Guido van Rossumb8b6d0c2003-06-28 21:53:52 +0000544
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000545/* Python "auto thread state" API. */
546#ifdef WITH_THREAD
547
548/* Keep this as a static, as it is not reliable! It can only
549 ever be compared to the state for the *current* thread.
550 * If not equal, then it doesn't matter that the actual
551 value may change immediately after comparison, as it can't
552 possibly change to the current thread's state.
553 * If equal, then the current thread holds the lock, so the value can't
554 change until we yield the lock.
555*/
556static int
557PyThreadState_IsCurrent(PyThreadState *tstate)
558{
559 /* Must be the tstate for this thread */
560 assert(PyGILState_GetThisThreadState()==tstate);
Jeffrey Yasskin39370832010-05-03 19:29:34 +0000561 return tstate == _Py_atomic_load_relaxed(&_PyThreadState_Current);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000562}
563
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000564/* Internal initialization/finalization functions called by
565 Py_Initialize/Py_Finalize
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000566*/
Tim Peters19717fa2004-10-09 17:38:29 +0000567void
568_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000569{
Tim Peters19717fa2004-10-09 17:38:29 +0000570 assert(i && t); /* must init with valid states */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000571 autoTLSkey = PyThread_create_key();
572 autoInterpreterState = i;
Tim Petersf9becec2004-10-09 22:47:13 +0000573 assert(PyThread_get_key_value(autoTLSkey) == NULL);
Michael W. Hudson188d4362005-06-20 16:52:57 +0000574 assert(t->gilstate_counter == 0);
575
576 _PyGILState_NoteThreadState(t);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000577}
578
Tim Peters19717fa2004-10-09 17:38:29 +0000579void
580_PyGILState_Fini(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000581{
582 PyThread_delete_key(autoTLSkey);
583 autoTLSkey = 0;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000584 autoInterpreterState = NULL;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000585}
586
Michael W. Hudson188d4362005-06-20 16:52:57 +0000587/* When a thread state is created for a thread by some mechanism other than
588 PyGILState_Ensure, it's important that the GILState machinery knows about
589 it so it doesn't try to create another thread state for the thread (this is
590 a better fix for SF bug #1010677 than the first one attempted).
591*/
Thomas Wouters89f507f2006-12-13 04:49:30 +0000592static void
Michael W. Hudson188d4362005-06-20 16:52:57 +0000593_PyGILState_NoteThreadState(PyThreadState* tstate)
594{
595 /* If autoTLSkey is 0, this must be the very first threadstate created
596 in Py_Initialize(). Don't do anything for now (we'll be back here
597 when _PyGILState_Init is called). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000598 if (!autoTLSkey)
Michael W. Hudson188d4362005-06-20 16:52:57 +0000599 return;
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000600
Michael W. Hudson188d4362005-06-20 16:52:57 +0000601 /* Stick the thread state for this thread in thread local storage.
602
603 The only situation where you can legitimately have more than one
604 thread state for an OS level thread is when there are multiple
605 interpreters, when:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000606
Michael W. Hudson188d4362005-06-20 16:52:57 +0000607 a) You shouldn't really be using the PyGILState_ APIs anyway,
608 and:
609
610 b) The slightly odd way PyThread_set_key_value works (see
611 comments by its implementation) means that the first thread
612 state created for that given OS level thread will "win",
613 which seems reasonable behaviour.
614 */
615 if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
616 Py_FatalError("Couldn't create autoTLSkey mapping");
617
618 /* PyGILState_Release must not try to delete this thread state. */
619 tstate->gilstate_counter = 1;
620}
621
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000622/* The public functions */
Tim Peters19717fa2004-10-09 17:38:29 +0000623PyThreadState *
624PyGILState_GetThisThreadState(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000625{
Tim Peters19717fa2004-10-09 17:38:29 +0000626 if (autoInterpreterState == NULL || autoTLSkey == 0)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000627 return NULL;
Tim Peters19717fa2004-10-09 17:38:29 +0000628 return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000629}
630
Tim Peters19717fa2004-10-09 17:38:29 +0000631PyGILState_STATE
632PyGILState_Ensure(void)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000633{
634 int current;
635 PyThreadState *tcur;
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000636 /* Note that we do not auto-init Python here - apart from
637 potential races with 2 threads auto-initializing, pep-311
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000638 spells out other issues. Embedders are expected to have
639 called Py_Initialize() and usually PyEval_InitThreads().
640 */
641 assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000642 tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
Tim Peters19717fa2004-10-09 17:38:29 +0000643 if (tcur == NULL) {
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000644 /* Create a new thread state for this thread */
645 tcur = PyThreadState_New(autoInterpreterState);
Tim Peters19717fa2004-10-09 17:38:29 +0000646 if (tcur == NULL)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000647 Py_FatalError("Couldn't create thread-state for new thread");
Michael W. Hudson188d4362005-06-20 16:52:57 +0000648 /* This is our thread state! We'll need to delete it in the
649 matching call to PyGILState_Release(). */
650 tcur->gilstate_counter = 0;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000651 current = 0; /* new thread state is never current */
Tim Peters19717fa2004-10-09 17:38:29 +0000652 }
653 else
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000654 current = PyThreadState_IsCurrent(tcur);
Tim Peters19717fa2004-10-09 17:38:29 +0000655 if (current == 0)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000656 PyEval_RestoreThread(tcur);
657 /* Update our counter in the thread-state - no need for locks:
658 - tcur will remain valid as we hold the GIL.
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000659 - the counter is safe as we are the only thread "allowed"
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000660 to modify this value
661 */
Tim Peters19717fa2004-10-09 17:38:29 +0000662 ++tcur->gilstate_counter;
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000663 return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
664}
665
Tim Peters19717fa2004-10-09 17:38:29 +0000666void
667PyGILState_Release(PyGILState_STATE oldstate)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000668{
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000669 PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
670 autoTLSkey);
Tim Peters19717fa2004-10-09 17:38:29 +0000671 if (tcur == NULL)
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000672 Py_FatalError("auto-releasing thread-state, "
673 "but no thread-state for this thread");
674 /* We must hold the GIL and have our thread state current */
675 /* XXX - remove the check - the assert should be fine,
Tim Peters4c1f5ec2004-10-09 17:25:05 +0000676 but while this is very new (April 2003), the extra check
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000677 by release-only users can't hurt.
678 */
Tim Peters19717fa2004-10-09 17:38:29 +0000679 if (! PyThreadState_IsCurrent(tcur))
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000680 Py_FatalError("This thread state must be current when releasing");
Tim Peters19717fa2004-10-09 17:38:29 +0000681 assert(PyThreadState_IsCurrent(tcur));
682 --tcur->gilstate_counter;
683 assert(tcur->gilstate_counter >= 0); /* illegal counter value */
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000684
Tim Petersfb1ffb02004-11-08 04:30:21 +0000685 /* If we're going to destroy this thread-state, we must
686 * clear it while the GIL is held, as destructors may run.
687 */
Tim Peters19717fa2004-10-09 17:38:29 +0000688 if (tcur->gilstate_counter == 0) {
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000689 /* can't have been locked when we created it */
Tim Peters19717fa2004-10-09 17:38:29 +0000690 assert(oldstate == PyGILState_UNLOCKED);
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000691 PyThreadState_Clear(tcur);
Tim Petersfb1ffb02004-11-08 04:30:21 +0000692 /* Delete the thread-state. Note this releases the GIL too!
693 * It's vital that the GIL be held here, to avoid shutdown
694 * races; see bugs 225673 and 1061968 (that nasty bug has a
695 * habit of coming back).
696 */
697 PyThreadState_DeleteCurrent();
Tim Peters89c0ec92004-10-10 05:30:40 +0000698 }
Tim Petersfb1ffb02004-11-08 04:30:21 +0000699 /* Release the lock if necessary */
700 else if (oldstate == PyGILState_UNLOCKED)
Michael W. Hudson774479c2005-04-18 08:46:17 +0000701 PyEval_SaveThread();
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000702}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000703
704#ifdef __cplusplus
705}
706#endif
707
Mark Hammond8d98d2c2003-04-19 15:41:53 +0000708#endif /* WITH_THREAD */
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000709
710