blob: 02195596093771f24e989c014f62f65468fae9d4 [file] [log] [blame]
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001
2/* Thread module */
3/* Interface to Sjoerd's portable C thread library */
4
Barry Warsawd0c10421996-12-17 00:05:22 +00005#include "Python.h"
Benjamin Petersonbec4d572009-10-10 01:16:07 +00006#include "structmember.h" /* offsetof */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00007
Guido van Rossumb6775db1994-08-01 11:34:53 +00008#ifndef WITH_THREAD
Guido van Rossuma027efa1997-05-05 20:56:21 +00009#error "Error! The rest of Python is not compiled with thread support."
Neal Norwitz884baa12002-09-05 21:31:04 +000010#error "Rerun configure, adding a --with-threads option."
Guido van Rossuma027efa1997-05-05 20:56:21 +000011#error "Then run `make clean' followed by `make'."
Guido van Rossumb6775db1994-08-01 11:34:53 +000012#endif
13
Guido van Rossum49b56061998-10-01 20:42:43 +000014#include "pythread.h"
Guido van Rossum1984f1e1992-08-04 12:41:02 +000015
Barry Warsawd0c10421996-12-17 00:05:22 +000016static PyObject *ThreadError;
Antoine Pitrou65c9c642009-10-30 17:25:12 +000017static long nb_threads = 0;
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +000018static PyObject *str_dict;
Guido van Rossum1984f1e1992-08-04 12:41:02 +000019
Victor Stinnerbd303c12013-11-07 23:07:29 +010020_Py_IDENTIFIER(stderr);
21
Guido van Rossum1984f1e1992-08-04 12:41:02 +000022/* Lock objects */
23
24typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyObject_HEAD
26 PyThread_type_lock lock_lock;
27 PyObject *in_weakreflist;
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +000028 char locked; /* for sanity checking */
Guido van Rossum1984f1e1992-08-04 12:41:02 +000029} lockobject;
30
Guido van Rossum1984f1e1992-08-04 12:41:02 +000031static void
Peter Schneider-Kamp3707efe2000-07-10 10:03:58 +000032lock_dealloc(lockobject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +000033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000034 if (self->in_weakreflist != NULL)
35 PyObject_ClearWeakRefs((PyObject *) self);
36 if (self->lock_lock != NULL) {
37 /* Unlock the lock so it's safe to free it */
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +000038 if (self->locked)
39 PyThread_release_lock(self->lock_lock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 PyThread_free_lock(self->lock_lock);
41 }
42 PyObject_Del(self);
Guido van Rossum1984f1e1992-08-04 12:41:02 +000043}
44
Antoine Pitrou810023d2010-12-15 22:59:16 +000045/* Helper to acquire an interruptible lock with a timeout. If the lock acquire
46 * is interrupted, signal handlers are run, and if they raise an exception,
47 * PY_LOCK_INTR is returned. Otherwise, PY_LOCK_ACQUIRED or PY_LOCK_FAILURE
Raymond Hettinger15f44ab2016-08-30 10:47:49 -070048 * are returned, depending on whether the lock can be acquired within the
Antoine Pitrou810023d2010-12-15 22:59:16 +000049 * timeout.
50 */
51static PyLockStatus
Victor Stinnerf5faad22015-03-28 03:52:05 +010052acquire_timed(PyThread_type_lock lock, _PyTime_t timeout)
Antoine Pitrou810023d2010-12-15 22:59:16 +000053{
54 PyLockStatus r;
Victor Stinnerf5faad22015-03-28 03:52:05 +010055 _PyTime_t endtime = 0;
56 _PyTime_t microseconds;
Antoine Pitrou810023d2010-12-15 22:59:16 +000057
Victor Stinnerf5faad22015-03-28 03:52:05 +010058 if (timeout > 0)
59 endtime = _PyTime_GetMonotonicClock() + timeout;
Antoine Pitrou810023d2010-12-15 22:59:16 +000060
61 do {
Victor Stinner869e1772015-03-30 03:49:14 +020062 microseconds = _PyTime_AsMicroseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinnerf5faad22015-03-28 03:52:05 +010063
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +000064 /* first a simple non-blocking try without releasing the GIL */
65 r = PyThread_acquire_lock_timed(lock, 0, 0);
66 if (r == PY_LOCK_FAILURE && microseconds != 0) {
67 Py_BEGIN_ALLOW_THREADS
68 r = PyThread_acquire_lock_timed(lock, microseconds, 1);
69 Py_END_ALLOW_THREADS
Victor Stinner357f5152013-11-05 15:10:19 +010070 }
Antoine Pitrou810023d2010-12-15 22:59:16 +000071
72 if (r == PY_LOCK_INTR) {
73 /* Run signal handlers if we were interrupted. Propagate
74 * exceptions from signal handlers, such as KeyboardInterrupt, by
75 * passing up PY_LOCK_INTR. */
76 if (Py_MakePendingCalls() < 0) {
77 return PY_LOCK_INTR;
78 }
79
80 /* If we're using a timeout, recompute the timeout after processing
81 * signals, since those can take time. */
Victor Stinnerf5faad22015-03-28 03:52:05 +010082 if (timeout > 0) {
83 timeout = endtime - _PyTime_GetMonotonicClock();
Antoine Pitrou810023d2010-12-15 22:59:16 +000084
85 /* Check for negative values, since those mean block forever.
86 */
Victor Stinner6aa446c2015-03-30 21:33:51 +020087 if (timeout < 0) {
Antoine Pitrou810023d2010-12-15 22:59:16 +000088 r = PY_LOCK_FAILURE;
89 }
90 }
91 }
92 } while (r == PY_LOCK_INTR); /* Retry if we were interrupted. */
93
94 return r;
95}
96
Victor Stinnerf5faad22015-03-28 03:52:05 +010097static int
98lock_acquire_parse_args(PyObject *args, PyObject *kwds,
99 _PyTime_t *timeout)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000100{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 char *kwlist[] = {"blocking", "timeout", NULL};
102 int blocking = 1;
Victor Stinnerf5faad22015-03-28 03:52:05 +0100103 PyObject *timeout_obj = NULL;
Victor Stinner13019fd2015-04-03 13:10:54 +0200104 const _PyTime_t unset_timeout = _PyTime_FromSeconds(-1);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000105
Victor Stinnerf5faad22015-03-28 03:52:05 +0100106 *timeout = unset_timeout ;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000107
Victor Stinnerf5faad22015-03-28 03:52:05 +0100108 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|iO:acquire", kwlist,
109 &blocking, &timeout_obj))
110 return -1;
111
112 if (timeout_obj
Victor Stinner869e1772015-03-30 03:49:14 +0200113 && _PyTime_FromSecondsObject(timeout,
114 timeout_obj, _PyTime_ROUND_CEILING) < 0)
Victor Stinnerf5faad22015-03-28 03:52:05 +0100115 return -1;
116
117 if (!blocking && *timeout != unset_timeout ) {
118 PyErr_SetString(PyExc_ValueError,
119 "can't specify a timeout for a non-blocking call");
120 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000121 }
Victor Stinnerf5faad22015-03-28 03:52:05 +0100122 if (*timeout < 0 && *timeout != unset_timeout) {
123 PyErr_SetString(PyExc_ValueError,
124 "timeout value must be positive");
125 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000126 }
127 if (!blocking)
Victor Stinnerf5faad22015-03-28 03:52:05 +0100128 *timeout = 0;
129 else if (*timeout != unset_timeout) {
130 _PyTime_t microseconds;
131
Victor Stinner869e1772015-03-30 03:49:14 +0200132 microseconds = _PyTime_AsMicroseconds(*timeout, _PyTime_ROUND_CEILING);
Victor Stinnerf5faad22015-03-28 03:52:05 +0100133 if (microseconds >= PY_TIMEOUT_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000134 PyErr_SetString(PyExc_OverflowError,
135 "timeout value is too large");
Victor Stinnerf5faad22015-03-28 03:52:05 +0100136 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000137 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000138 }
Victor Stinnerf5faad22015-03-28 03:52:05 +0100139 return 0;
140}
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000141
Victor Stinnerf5faad22015-03-28 03:52:05 +0100142static PyObject *
143lock_PyThread_acquire_lock(lockobject *self, PyObject *args, PyObject *kwds)
144{
145 _PyTime_t timeout;
146 PyLockStatus r;
147
148 if (lock_acquire_parse_args(args, kwds, &timeout) < 0)
149 return NULL;
150
151 r = acquire_timed(self->lock_lock, timeout);
Antoine Pitrou810023d2010-12-15 22:59:16 +0000152 if (r == PY_LOCK_INTR) {
153 return NULL;
154 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000155
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000156 if (r == PY_LOCK_ACQUIRED)
157 self->locked = 1;
Antoine Pitrou810023d2010-12-15 22:59:16 +0000158 return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000159}
160
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000161PyDoc_STRVAR(acquire_doc,
Berker Peksag720e6552016-05-02 12:25:35 +0300162"acquire(blocking=True, timeout=-1) -> bool\n\
Guido van Rossumf6694362006-03-10 02:28:35 +0000163(acquire_lock() is an obsolete synonym)\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000164\n\
165Lock the lock. Without argument, this blocks if the lock is already\n\
166locked (even by the same thread), waiting for another thread to release\n\
R David Murray95b71102013-02-04 10:15:58 -0500167the lock, and return True once the lock is acquired.\n\
Guido van Rossum8fdc75b2002-04-07 06:32:21 +0000168With an argument, this will only block if the argument is true,\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000169and the return value reflects whether the lock is acquired.\n\
Antoine Pitrou810023d2010-12-15 22:59:16 +0000170The blocking operation is interruptible.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000171
Barry Warsawd0c10421996-12-17 00:05:22 +0000172static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +0000173lock_PyThread_release_lock(lockobject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 /* Sanity check: the lock must be locked */
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000176 if (!self->locked) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 PyErr_SetString(ThreadError, "release unlocked lock");
178 return NULL;
179 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 PyThread_release_lock(self->lock_lock);
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000182 self->locked = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 Py_INCREF(Py_None);
184 return Py_None;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000185}
186
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000187PyDoc_STRVAR(release_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000188"release()\n\
Guido van Rossumf6694362006-03-10 02:28:35 +0000189(release_lock() is an obsolete synonym)\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000190\n\
191Release the lock, allowing another thread that is blocked waiting for\n\
192the lock to acquire the lock. The lock must be in the locked state,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000193but it needn't be locked by the same thread that unlocks it.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000194
Barry Warsawd0c10421996-12-17 00:05:22 +0000195static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +0000196lock_locked_lock(lockobject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000197{
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000198 return PyBool_FromLong((long)self->locked);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000199}
200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000201PyDoc_STRVAR(locked_doc,
Guido van Rossum8fdc75b2002-04-07 06:32:21 +0000202"locked() -> bool\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000203(locked_lock() is an obsolete synonym)\n\
204\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000205Return whether the lock is in the locked state.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000206
Raymond Hettinger62f4dad2014-05-25 18:22:35 -0700207static PyObject *
208lock_repr(lockobject *self)
209{
210 return PyUnicode_FromFormat("<%s %s object at %p>",
211 self->locked ? "locked" : "unlocked", Py_TYPE(self)->tp_name, self);
212}
213
Barry Warsawd0c10421996-12-17 00:05:22 +0000214static PyMethodDef lock_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
216 METH_VARARGS | METH_KEYWORDS, acquire_doc},
217 {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
218 METH_VARARGS | METH_KEYWORDS, acquire_doc},
219 {"release_lock", (PyCFunction)lock_PyThread_release_lock,
220 METH_NOARGS, release_doc},
221 {"release", (PyCFunction)lock_PyThread_release_lock,
222 METH_NOARGS, release_doc},
223 {"locked_lock", (PyCFunction)lock_locked_lock,
224 METH_NOARGS, locked_doc},
225 {"locked", (PyCFunction)lock_locked_lock,
226 METH_NOARGS, locked_doc},
227 {"__enter__", (PyCFunction)lock_PyThread_acquire_lock,
228 METH_VARARGS | METH_KEYWORDS, acquire_doc},
229 {"__exit__", (PyCFunction)lock_PyThread_release_lock,
230 METH_VARARGS, release_doc},
231 {NULL, NULL} /* sentinel */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000232};
233
Barry Warsawd0c10421996-12-17 00:05:22 +0000234static PyTypeObject Locktype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyVarObject_HEAD_INIT(&PyType_Type, 0)
236 "_thread.lock", /*tp_name*/
237 sizeof(lockobject), /*tp_size*/
238 0, /*tp_itemsize*/
239 /* methods */
240 (destructor)lock_dealloc, /*tp_dealloc*/
241 0, /*tp_print*/
242 0, /*tp_getattr*/
243 0, /*tp_setattr*/
244 0, /*tp_reserved*/
Raymond Hettinger62f4dad2014-05-25 18:22:35 -0700245 (reprfunc)lock_repr, /*tp_repr*/
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 0, /*tp_as_number*/
247 0, /*tp_as_sequence*/
248 0, /*tp_as_mapping*/
249 0, /*tp_hash*/
250 0, /*tp_call*/
251 0, /*tp_str*/
252 0, /*tp_getattro*/
253 0, /*tp_setattro*/
254 0, /*tp_as_buffer*/
255 Py_TPFLAGS_DEFAULT, /*tp_flags*/
256 0, /*tp_doc*/
257 0, /*tp_traverse*/
258 0, /*tp_clear*/
259 0, /*tp_richcompare*/
260 offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/
261 0, /*tp_iter*/
262 0, /*tp_iternext*/
263 lock_methods, /*tp_methods*/
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000264};
265
Antoine Pitrou434736a2009-11-10 18:46:01 +0000266/* Recursive lock objects */
267
268typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 PyObject_HEAD
270 PyThread_type_lock rlock_lock;
271 long rlock_owner;
272 unsigned long rlock_count;
273 PyObject *in_weakreflist;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000274} rlockobject;
275
276static void
277rlock_dealloc(rlockobject *self)
278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (self->in_weakreflist != NULL)
280 PyObject_ClearWeakRefs((PyObject *) self);
Victor Stinner357f5152013-11-05 15:10:19 +0100281 /* self->rlock_lock can be NULL if PyThread_allocate_lock() failed
282 in rlock_new() */
283 if (self->rlock_lock != NULL) {
284 /* Unlock the lock so it's safe to free it */
285 if (self->rlock_count > 0)
286 PyThread_release_lock(self->rlock_lock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287
Victor Stinner357f5152013-11-05 15:10:19 +0100288 PyThread_free_lock(self->rlock_lock);
289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 Py_TYPE(self)->tp_free(self);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000291}
292
293static PyObject *
294rlock_acquire(rlockobject *self, PyObject *args, PyObject *kwds)
295{
Victor Stinnerf5faad22015-03-28 03:52:05 +0100296 _PyTime_t timeout;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000297 long tid;
Antoine Pitrou810023d2010-12-15 22:59:16 +0000298 PyLockStatus r = PY_LOCK_ACQUIRED;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000299
Victor Stinnerf5faad22015-03-28 03:52:05 +0100300 if (lock_acquire_parse_args(args, kwds, &timeout) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return NULL;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000302
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 tid = PyThread_get_thread_ident();
304 if (self->rlock_count > 0 && tid == self->rlock_owner) {
305 unsigned long count = self->rlock_count + 1;
306 if (count <= self->rlock_count) {
307 PyErr_SetString(PyExc_OverflowError,
308 "Internal lock count overflowed");
309 return NULL;
310 }
311 self->rlock_count = count;
312 Py_RETURN_TRUE;
313 }
Victor Stinnerf5faad22015-03-28 03:52:05 +0100314 r = acquire_timed(self->rlock_lock, timeout);
Antoine Pitrou810023d2010-12-15 22:59:16 +0000315 if (r == PY_LOCK_ACQUIRED) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 assert(self->rlock_count == 0);
317 self->rlock_owner = tid;
318 self->rlock_count = 1;
319 }
Antoine Pitrou810023d2010-12-15 22:59:16 +0000320 else if (r == PY_LOCK_INTR) {
321 return NULL;
322 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323
Antoine Pitrou810023d2010-12-15 22:59:16 +0000324 return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000325}
326
327PyDoc_STRVAR(rlock_acquire_doc,
328"acquire(blocking=True) -> bool\n\
329\n\
330Lock the lock. `blocking` indicates whether we should wait\n\
331for the lock to be available or not. If `blocking` is False\n\
332and another thread holds the lock, the method will return False\n\
333immediately. If `blocking` is True and another thread holds\n\
334the lock, the method will wait for the lock to be released,\n\
335take it and then return True.\n\
Antoine Pitrou810023d2010-12-15 22:59:16 +0000336(note: the blocking operation is interruptible.)\n\
Antoine Pitrou434736a2009-11-10 18:46:01 +0000337\n\
338In all other cases, the method will return True immediately.\n\
339Precisely, if the current thread already holds the lock, its\n\
340internal counter is simply incremented. If nobody holds the lock,\n\
341the lock is taken and its internal counter initialized to 1.");
342
343static PyObject *
344rlock_release(rlockobject *self)
345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 long tid = PyThread_get_thread_ident();
Antoine Pitrou434736a2009-11-10 18:46:01 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (self->rlock_count == 0 || self->rlock_owner != tid) {
349 PyErr_SetString(PyExc_RuntimeError,
350 "cannot release un-acquired lock");
351 return NULL;
352 }
353 if (--self->rlock_count == 0) {
354 self->rlock_owner = 0;
355 PyThread_release_lock(self->rlock_lock);
356 }
357 Py_RETURN_NONE;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000358}
359
360PyDoc_STRVAR(rlock_release_doc,
361"release()\n\
362\n\
363Release the lock, allowing another thread that is blocked waiting for\n\
364the lock to acquire the lock. The lock must be in the locked state,\n\
365and must be locked by the same thread that unlocks it; otherwise a\n\
366`RuntimeError` is raised.\n\
367\n\
368Do note that if the lock was acquire()d several times in a row by the\n\
369current thread, release() needs to be called as many times for the lock\n\
370to be available for other threads.");
371
372static PyObject *
Victor Stinnere8794522014-01-02 12:47:24 +0100373rlock_acquire_restore(rlockobject *self, PyObject *args)
Antoine Pitrou434736a2009-11-10 18:46:01 +0000374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 long owner;
376 unsigned long count;
377 int r = 1;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000378
Victor Stinnere8794522014-01-02 12:47:24 +0100379 if (!PyArg_ParseTuple(args, "(kl):_acquire_restore", &count, &owner))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 return NULL;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 if (!PyThread_acquire_lock(self->rlock_lock, 0)) {
383 Py_BEGIN_ALLOW_THREADS
384 r = PyThread_acquire_lock(self->rlock_lock, 1);
385 Py_END_ALLOW_THREADS
386 }
387 if (!r) {
388 PyErr_SetString(ThreadError, "couldn't acquire lock");
389 return NULL;
390 }
391 assert(self->rlock_count == 0);
392 self->rlock_owner = owner;
393 self->rlock_count = count;
394 Py_RETURN_NONE;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000395}
396
397PyDoc_STRVAR(rlock_acquire_restore_doc,
398"_acquire_restore(state) -> None\n\
399\n\
400For internal use by `threading.Condition`.");
401
402static PyObject *
403rlock_release_save(rlockobject *self)
404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 long owner;
406 unsigned long count;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000407
Victor Stinnerc2824d42011-04-24 23:41:33 +0200408 if (self->rlock_count == 0) {
409 PyErr_SetString(PyExc_RuntimeError,
410 "cannot release un-acquired lock");
411 return NULL;
412 }
413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 owner = self->rlock_owner;
415 count = self->rlock_count;
416 self->rlock_count = 0;
417 self->rlock_owner = 0;
418 PyThread_release_lock(self->rlock_lock);
419 return Py_BuildValue("kl", count, owner);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000420}
421
422PyDoc_STRVAR(rlock_release_save_doc,
423"_release_save() -> tuple\n\
424\n\
425For internal use by `threading.Condition`.");
426
427
428static PyObject *
429rlock_is_owned(rlockobject *self)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 long tid = PyThread_get_thread_ident();
432
433 if (self->rlock_count > 0 && self->rlock_owner == tid) {
434 Py_RETURN_TRUE;
435 }
436 Py_RETURN_FALSE;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000437}
438
439PyDoc_STRVAR(rlock_is_owned_doc,
440"_is_owned() -> bool\n\
441\n\
442For internal use by `threading.Condition`.");
443
444static PyObject *
445rlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 rlockobject *self;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 self = (rlockobject *) type->tp_alloc(type, 0);
450 if (self != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 self->in_weakreflist = NULL;
452 self->rlock_owner = 0;
453 self->rlock_count = 0;
Victor Stinner357f5152013-11-05 15:10:19 +0100454
455 self->rlock_lock = PyThread_allocate_lock();
456 if (self->rlock_lock == NULL) {
457 Py_DECREF(self);
458 PyErr_SetString(ThreadError, "can't allocate lock");
459 return NULL;
460 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 }
Antoine Pitrou434736a2009-11-10 18:46:01 +0000462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 return (PyObject *) self;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000464}
465
466static PyObject *
467rlock_repr(rlockobject *self)
468{
Raymond Hettinger62f4dad2014-05-25 18:22:35 -0700469 return PyUnicode_FromFormat("<%s %s object owner=%ld count=%lu at %p>",
470 self->rlock_count ? "locked" : "unlocked",
471 Py_TYPE(self)->tp_name, self->rlock_owner,
472 self->rlock_count, self);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000473}
474
475
476static PyMethodDef rlock_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 {"acquire", (PyCFunction)rlock_acquire,
478 METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
479 {"release", (PyCFunction)rlock_release,
480 METH_NOARGS, rlock_release_doc},
481 {"_is_owned", (PyCFunction)rlock_is_owned,
482 METH_NOARGS, rlock_is_owned_doc},
483 {"_acquire_restore", (PyCFunction)rlock_acquire_restore,
Victor Stinnere8794522014-01-02 12:47:24 +0100484 METH_VARARGS, rlock_acquire_restore_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 {"_release_save", (PyCFunction)rlock_release_save,
486 METH_NOARGS, rlock_release_save_doc},
487 {"__enter__", (PyCFunction)rlock_acquire,
488 METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
489 {"__exit__", (PyCFunction)rlock_release,
490 METH_VARARGS, rlock_release_doc},
491 {NULL, NULL} /* sentinel */
Antoine Pitrou434736a2009-11-10 18:46:01 +0000492};
493
494
495static PyTypeObject RLocktype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 PyVarObject_HEAD_INIT(&PyType_Type, 0)
497 "_thread.RLock", /*tp_name*/
498 sizeof(rlockobject), /*tp_size*/
499 0, /*tp_itemsize*/
500 /* methods */
501 (destructor)rlock_dealloc, /*tp_dealloc*/
502 0, /*tp_print*/
503 0, /*tp_getattr*/
504 0, /*tp_setattr*/
505 0, /*tp_reserved*/
506 (reprfunc)rlock_repr, /*tp_repr*/
507 0, /*tp_as_number*/
508 0, /*tp_as_sequence*/
509 0, /*tp_as_mapping*/
510 0, /*tp_hash*/
511 0, /*tp_call*/
512 0, /*tp_str*/
513 0, /*tp_getattro*/
514 0, /*tp_setattro*/
515 0, /*tp_as_buffer*/
516 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
517 0, /*tp_doc*/
518 0, /*tp_traverse*/
519 0, /*tp_clear*/
520 0, /*tp_richcompare*/
521 offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/
522 0, /*tp_iter*/
523 0, /*tp_iternext*/
524 rlock_methods, /*tp_methods*/
525 0, /* tp_members */
526 0, /* tp_getset */
527 0, /* tp_base */
528 0, /* tp_dict */
529 0, /* tp_descr_get */
530 0, /* tp_descr_set */
531 0, /* tp_dictoffset */
532 0, /* tp_init */
533 PyType_GenericAlloc, /* tp_alloc */
534 rlock_new /* tp_new */
Antoine Pitrou434736a2009-11-10 18:46:01 +0000535};
536
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000537static lockobject *
538newlockobject(void)
539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 lockobject *self;
541 self = PyObject_New(lockobject, &Locktype);
542 if (self == NULL)
543 return NULL;
544 self->lock_lock = PyThread_allocate_lock();
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000545 self->locked = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 self->in_weakreflist = NULL;
547 if (self->lock_lock == NULL) {
548 Py_DECREF(self);
549 PyErr_SetString(ThreadError, "can't allocate lock");
550 return NULL;
551 }
552 return self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000553}
554
Jim Fultond15dc062004-07-14 19:11:50 +0000555/* Thread-local objects */
556
557#include "structmember.h"
558
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000559/* Quick overview:
560
561 We need to be able to reclaim reference cycles as soon as possible
562 (both when a thread is being terminated, or a thread-local object
563 becomes unreachable from user data). Constraints:
564 - it must not be possible for thread-state dicts to be involved in
565 reference cycles (otherwise the cyclic GC will refuse to consider
566 objects referenced from a reachable thread-state dict, even though
567 local_dealloc would clear them)
568 - the death of a thread-state dict must still imply destruction of the
569 corresponding local dicts in all thread-local objects.
570
571 Our implementation uses small "localdummy" objects in order to break
572 the reference chain. These trivial objects are hashable (using the
573 default scheme of identity hashing) and weakrefable.
574 Each thread-state holds a separate localdummy for each local object
575 (as a /strong reference/),
576 and each thread-local object holds a dict mapping /weak references/
577 of localdummies to local dicts.
578
579 Therefore:
580 - only the thread-state dict holds a strong reference to the dummies
581 - only the thread-local object holds a strong reference to the local dicts
582 - only outside objects (application- or library-level) hold strong
583 references to the thread-local objects
584 - as soon as a thread-state dict is destroyed, the weakref callbacks of all
585 dummies attached to that thread are called, and destroy the corresponding
586 local dicts from thread-local objects
587 - as soon as a thread-local object is destroyed, its local dicts are
588 destroyed and its dummies are manually removed from all thread states
589 - the GC can do its work correctly when a thread-local object is dangling,
590 without any interference from the thread-state dicts
591
592 As an additional optimization, each localdummy holds a borrowed reference
593 to the corresponding localdict. This borrowed reference is only used
594 by the thread-local object which has created the localdummy, which should
595 guarantee that the localdict still exists when accessed.
596*/
597
598typedef struct {
599 PyObject_HEAD
600 PyObject *localdict; /* Borrowed reference! */
601 PyObject *weakreflist; /* List of weak references to self */
602} localdummyobject;
603
604static void
605localdummy_dealloc(localdummyobject *self)
606{
607 if (self->weakreflist != NULL)
608 PyObject_ClearWeakRefs((PyObject *) self);
609 Py_TYPE(self)->tp_free((PyObject*)self);
610}
611
612static PyTypeObject localdummytype = {
613 PyVarObject_HEAD_INIT(NULL, 0)
614 /* tp_name */ "_thread._localdummy",
615 /* tp_basicsize */ sizeof(localdummyobject),
616 /* tp_itemsize */ 0,
617 /* tp_dealloc */ (destructor)localdummy_dealloc,
618 /* tp_print */ 0,
619 /* tp_getattr */ 0,
620 /* tp_setattr */ 0,
621 /* tp_reserved */ 0,
622 /* tp_repr */ 0,
623 /* tp_as_number */ 0,
624 /* tp_as_sequence */ 0,
625 /* tp_as_mapping */ 0,
626 /* tp_hash */ 0,
627 /* tp_call */ 0,
628 /* tp_str */ 0,
629 /* tp_getattro */ 0,
630 /* tp_setattro */ 0,
631 /* tp_as_buffer */ 0,
632 /* tp_flags */ Py_TPFLAGS_DEFAULT,
633 /* tp_doc */ "Thread-local dummy",
634 /* tp_traverse */ 0,
635 /* tp_clear */ 0,
636 /* tp_richcompare */ 0,
637 /* tp_weaklistoffset */ offsetof(localdummyobject, weakreflist)
638};
639
640
Jim Fultond15dc062004-07-14 19:11:50 +0000641typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 PyObject_HEAD
643 PyObject *key;
644 PyObject *args;
645 PyObject *kw;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000646 PyObject *weakreflist; /* List of weak references to self */
647 /* A {localdummy weakref -> localdict} dict */
648 PyObject *dummies;
649 /* The callback for weakrefs to localdummies */
650 PyObject *wr_callback;
Jim Fultond15dc062004-07-14 19:11:50 +0000651} localobject;
652
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000653/* Forward declaration */
654static PyObject *_ldict(localobject *self);
655static PyObject *_localdummy_destroyed(PyObject *meth_self, PyObject *dummyweakref);
656
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000657/* Create and register the dummy for the current thread.
658 Returns a borrowed reference of the corresponding local dict */
659static PyObject *
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000660_local_create_dummy(localobject *self)
661{
662 PyObject *tdict, *ldict = NULL, *wr = NULL;
663 localdummyobject *dummy = NULL;
664 int r;
665
666 tdict = PyThreadState_GetDict();
667 if (tdict == NULL) {
668 PyErr_SetString(PyExc_SystemError,
669 "Couldn't get thread-state dictionary");
670 goto err;
671 }
672
673 ldict = PyDict_New();
674 if (ldict == NULL)
675 goto err;
676 dummy = (localdummyobject *) localdummytype.tp_alloc(&localdummytype, 0);
677 if (dummy == NULL)
678 goto err;
679 dummy->localdict = ldict;
680 wr = PyWeakref_NewRef((PyObject *) dummy, self->wr_callback);
681 if (wr == NULL)
682 goto err;
683
684 /* As a side-effect, this will cache the weakref's hash before the
685 dummy gets deleted */
686 r = PyDict_SetItem(self->dummies, wr, ldict);
687 if (r < 0)
688 goto err;
689 Py_CLEAR(wr);
690 r = PyDict_SetItem(tdict, self->key, (PyObject *) dummy);
691 if (r < 0)
692 goto err;
693 Py_CLEAR(dummy);
694
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000695 Py_DECREF(ldict);
696 return ldict;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000697
698err:
699 Py_XDECREF(ldict);
700 Py_XDECREF(wr);
701 Py_XDECREF(dummy);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000702 return NULL;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000703}
704
Jim Fultond15dc062004-07-14 19:11:50 +0000705static PyObject *
706local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 localobject *self;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000709 PyObject *wr;
710 static PyMethodDef wr_callback_def = {
711 "_localdummy_destroyed", (PyCFunction) _localdummy_destroyed, METH_O
712 };
Jim Fultond15dc062004-07-14 19:11:50 +0000713
Serhiy Storchakafa494fd2015-05-30 17:45:22 +0300714 if (type->tp_init == PyBaseObject_Type.tp_init) {
715 int rc = 0;
716 if (args != NULL)
717 rc = PyObject_IsTrue(args);
718 if (rc == 0 && kw != NULL)
719 rc = PyObject_IsTrue(kw);
720 if (rc != 0) {
721 if (rc > 0)
722 PyErr_SetString(PyExc_TypeError,
723 "Initialization arguments are not supported");
724 return NULL;
725 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 }
Jim Fultond15dc062004-07-14 19:11:50 +0000727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 self = (localobject *)type->tp_alloc(type, 0);
729 if (self == NULL)
730 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +0000731
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000732 Py_XINCREF(args);
733 self->args = args;
734 Py_XINCREF(kw);
735 self->kw = kw;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 self->key = PyUnicode_FromFormat("thread.local.%p", self);
737 if (self->key == NULL)
738 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000739
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000740 self->dummies = PyDict_New();
741 if (self->dummies == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000743
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000744 /* We use a weak reference to self in the callback closure
745 in order to avoid spurious reference cycles */
746 wr = PyWeakref_NewRef((PyObject *) self, NULL);
747 if (wr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 goto err;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +0200749 self->wr_callback = PyCFunction_NewEx(&wr_callback_def, wr, NULL);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000750 Py_DECREF(wr);
751 if (self->wr_callback == NULL)
752 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000753
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000754 if (_local_create_dummy(self) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000755 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000757 return (PyObject *)self;
Michael W. Hudson2368b3c2005-06-15 12:48:40 +0000758
759 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 Py_DECREF(self);
761 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +0000762}
763
764static int
765local_traverse(localobject *self, visitproc visit, void *arg)
766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 Py_VISIT(self->args);
768 Py_VISIT(self->kw);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000769 Py_VISIT(self->dummies);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000770 return 0;
Jim Fultond15dc062004-07-14 19:11:50 +0000771}
772
773static int
774local_clear(localobject *self)
775{
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000776 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 Py_CLEAR(self->args);
778 Py_CLEAR(self->kw);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000779 Py_CLEAR(self->dummies);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000780 Py_CLEAR(self->wr_callback);
781 /* Remove all strong references to dummies from the thread states */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 if (self->key
783 && (tstate = PyThreadState_Get())
784 && tstate->interp) {
785 for(tstate = PyInterpreterState_ThreadHead(tstate->interp);
786 tstate;
787 tstate = PyThreadState_Next(tstate))
788 if (tstate->dict &&
789 PyDict_GetItem(tstate->dict, self->key))
790 PyDict_DelItem(tstate->dict, self->key);
791 }
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000792 return 0;
793}
Jim Fultond15dc062004-07-14 19:11:50 +0000794
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000795static void
796local_dealloc(localobject *self)
797{
798 /* Weakrefs must be invalidated right now, otherwise they can be used
799 from code called below, which is very dangerous since Py_REFCNT(self) == 0 */
800 if (self->weakreflist != NULL)
801 PyObject_ClearWeakRefs((PyObject *) self);
802
803 PyObject_GC_UnTrack(self);
804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000805 local_clear(self);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000806 Py_XDECREF(self->key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000807 Py_TYPE(self)->tp_free((PyObject*)self);
Jim Fultond15dc062004-07-14 19:11:50 +0000808}
809
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000810/* Returns a borrowed reference to the local dict, creating it if necessary */
Jim Fultond15dc062004-07-14 19:11:50 +0000811static PyObject *
812_ldict(localobject *self)
813{
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000814 PyObject *tdict, *ldict, *dummy;
Jim Fultond15dc062004-07-14 19:11:50 +0000815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000816 tdict = PyThreadState_GetDict();
817 if (tdict == NULL) {
818 PyErr_SetString(PyExc_SystemError,
819 "Couldn't get thread-state dictionary");
820 return NULL;
821 }
Jim Fultond15dc062004-07-14 19:11:50 +0000822
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000823 dummy = PyDict_GetItem(tdict, self->key);
824 if (dummy == NULL) {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000825 ldict = _local_create_dummy(self);
826 if (ldict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000827 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init &&
830 Py_TYPE(self)->tp_init((PyObject*)self,
831 self->args, self->kw) < 0) {
832 /* we need to get rid of ldict from thread so
833 we create a new one the next time we do an attr
Ezio Melotti42da6632011-03-15 05:18:48 +0200834 access */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyDict_DelItem(tdict, self->key);
836 return NULL;
837 }
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000838 }
839 else {
840 assert(Py_TYPE(dummy) == &localdummytype);
841 ldict = ((localdummyobject *) dummy)->localdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 }
Jim Fultond15dc062004-07-14 19:11:50 +0000843
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 return ldict;
Jim Fultond15dc062004-07-14 19:11:50 +0000845}
846
Jim Fultond15dc062004-07-14 19:11:50 +0000847static int
848local_setattro(localobject *self, PyObject *name, PyObject *v)
849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyObject *ldict;
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000851 int r;
Jim Fultond15dc062004-07-14 19:11:50 +0000852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000853 ldict = _ldict(self);
854 if (ldict == NULL)
855 return -1;
856
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000857 r = PyObject_RichCompareBool(name, str_dict, Py_EQ);
858 if (r == 1) {
859 PyErr_Format(PyExc_AttributeError,
860 "'%.50s' object attribute '%U' is read-only",
861 Py_TYPE(self)->tp_name, name);
862 return -1;
863 }
864 if (r == -1)
865 return -1;
Jim Fultond15dc062004-07-14 19:11:50 +0000866
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000867 return _PyObject_GenericSetAttrWithDict((PyObject *)self, name, v, ldict);
Jim Fultond15dc062004-07-14 19:11:50 +0000868}
869
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000870static PyObject *local_getattro(localobject *, PyObject *);
871
Jim Fultond15dc062004-07-14 19:11:50 +0000872static PyTypeObject localtype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 PyVarObject_HEAD_INIT(NULL, 0)
874 /* tp_name */ "_thread._local",
875 /* tp_basicsize */ sizeof(localobject),
876 /* tp_itemsize */ 0,
877 /* tp_dealloc */ (destructor)local_dealloc,
878 /* tp_print */ 0,
879 /* tp_getattr */ 0,
880 /* tp_setattr */ 0,
881 /* tp_reserved */ 0,
882 /* tp_repr */ 0,
883 /* tp_as_number */ 0,
884 /* tp_as_sequence */ 0,
885 /* tp_as_mapping */ 0,
886 /* tp_hash */ 0,
887 /* tp_call */ 0,
888 /* tp_str */ 0,
889 /* tp_getattro */ (getattrofunc)local_getattro,
890 /* tp_setattro */ (setattrofunc)local_setattro,
891 /* tp_as_buffer */ 0,
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000892 /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
893 | Py_TPFLAGS_HAVE_GC,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 /* tp_doc */ "Thread-local data",
895 /* tp_traverse */ (traverseproc)local_traverse,
896 /* tp_clear */ (inquiry)local_clear,
897 /* tp_richcompare */ 0,
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000898 /* tp_weaklistoffset */ offsetof(localobject, weakreflist),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 /* tp_iter */ 0,
900 /* tp_iternext */ 0,
901 /* tp_methods */ 0,
902 /* tp_members */ 0,
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000903 /* tp_getset */ 0,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 /* tp_base */ 0,
905 /* tp_dict */ 0, /* internal use */
906 /* tp_descr_get */ 0,
907 /* tp_descr_set */ 0,
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000908 /* tp_dictoffset */ 0,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 /* tp_init */ 0,
910 /* tp_alloc */ 0,
911 /* tp_new */ local_new,
912 /* tp_free */ 0, /* Low-level free-mem routine */
913 /* tp_is_gc */ 0, /* For PyObject_IS_GC */
Jim Fultond15dc062004-07-14 19:11:50 +0000914};
915
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000916static PyObject *
917local_getattro(localobject *self, PyObject *name)
918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyObject *ldict, *value;
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000920 int r;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 ldict = _ldict(self);
923 if (ldict == NULL)
924 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000925
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000926 r = PyObject_RichCompareBool(name, str_dict, Py_EQ);
927 if (r == 1) {
928 Py_INCREF(ldict);
929 return ldict;
930 }
931 if (r == -1)
932 return NULL;
933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 if (Py_TYPE(self) != &localtype)
935 /* use generic lookup for subtypes */
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000936 return _PyObject_GenericGetAttrWithDict((PyObject *)self, name, ldict);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 /* Optimization: just look in dict ourselves */
939 value = PyDict_GetItem(ldict, name);
940 if (value == NULL)
941 /* Fall back on generic to get __class__ and __dict__ */
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000942 return _PyObject_GenericGetAttrWithDict((PyObject *)self, name, ldict);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 Py_INCREF(value);
945 return value;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000946}
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000947
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000948/* Called when a dummy is destroyed. */
949static PyObject *
950_localdummy_destroyed(PyObject *localweakref, PyObject *dummyweakref)
951{
952 PyObject *obj;
953 localobject *self;
954 assert(PyWeakref_CheckRef(localweakref));
955 obj = PyWeakref_GET_OBJECT(localweakref);
956 if (obj == Py_None)
957 Py_RETURN_NONE;
958 Py_INCREF(obj);
959 assert(PyObject_TypeCheck(obj, &localtype));
960 /* If the thread-local object is still alive and not being cleared,
961 remove the corresponding local dict */
962 self = (localobject *) obj;
963 if (self->dummies != NULL) {
964 PyObject *ldict;
965 ldict = PyDict_GetItem(self->dummies, dummyweakref);
966 if (ldict != NULL) {
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000967 PyDict_DelItem(self->dummies, dummyweakref);
968 }
969 if (PyErr_Occurred())
970 PyErr_WriteUnraisable(obj);
971 }
972 Py_DECREF(obj);
973 Py_RETURN_NONE;
974}
975
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000976/* Module functions */
977
Guido van Rossuma027efa1997-05-05 20:56:21 +0000978struct bootstate {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 PyInterpreterState *interp;
980 PyObject *func;
981 PyObject *args;
982 PyObject *keyw;
983 PyThreadState *tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000984};
985
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000986static void
Peter Schneider-Kamp3707efe2000-07-10 10:03:58 +0000987t_bootstrap(void *boot_raw)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 struct bootstate *boot = (struct bootstate *) boot_raw;
990 PyThreadState *tstate;
991 PyObject *res;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 tstate = boot->tstate;
994 tstate->thread_id = PyThread_get_thread_ident();
995 _PyThreadState_Init(tstate);
996 PyEval_AcquireThread(tstate);
997 nb_threads++;
998 res = PyEval_CallObjectWithKeywords(
999 boot->func, boot->args, boot->keyw);
1000 if (res == NULL) {
1001 if (PyErr_ExceptionMatches(PyExc_SystemExit))
1002 PyErr_Clear();
1003 else {
1004 PyObject *file;
Benjamin Petersone9000962012-04-02 11:15:17 -04001005 PyObject *exc, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 PySys_WriteStderr(
1007 "Unhandled exception in thread started by ");
Benjamin Petersone9000962012-04-02 11:15:17 -04001008 PyErr_Fetch(&exc, &value, &tb);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001009 file = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (file != NULL && file != Py_None)
1011 PyFile_WriteObject(boot->func, file, 0);
1012 else
1013 PyObject_Print(boot->func, stderr, 0);
1014 PySys_WriteStderr("\n");
Benjamin Petersone9000962012-04-02 11:15:17 -04001015 PyErr_Restore(exc, value, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 PyErr_PrintEx(0);
1017 }
1018 }
1019 else
1020 Py_DECREF(res);
1021 Py_DECREF(boot->func);
1022 Py_DECREF(boot->args);
1023 Py_XDECREF(boot->keyw);
1024 PyMem_DEL(boot_raw);
1025 nb_threads--;
1026 PyThreadState_Clear(tstate);
1027 PyThreadState_DeleteCurrent();
1028 PyThread_exit_thread();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001029}
1030
Barry Warsawd0c10421996-12-17 00:05:22 +00001031static PyObject *
Peter Schneider-Kamp3707efe2000-07-10 10:03:58 +00001032thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyObject *func, *args, *keyw = NULL;
1035 struct bootstate *boot;
1036 long ident;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3,
1039 &func, &args, &keyw))
1040 return NULL;
1041 if (!PyCallable_Check(func)) {
1042 PyErr_SetString(PyExc_TypeError,
1043 "first arg must be callable");
1044 return NULL;
1045 }
1046 if (!PyTuple_Check(args)) {
1047 PyErr_SetString(PyExc_TypeError,
1048 "2nd arg must be a tuple");
1049 return NULL;
1050 }
1051 if (keyw != NULL && !PyDict_Check(keyw)) {
1052 PyErr_SetString(PyExc_TypeError,
1053 "optional 3rd arg must be a dictionary");
1054 return NULL;
1055 }
1056 boot = PyMem_NEW(struct bootstate, 1);
1057 if (boot == NULL)
1058 return PyErr_NoMemory();
1059 boot->interp = PyThreadState_GET()->interp;
1060 boot->func = func;
1061 boot->args = args;
1062 boot->keyw = keyw;
1063 boot->tstate = _PyThreadState_Prealloc(boot->interp);
1064 if (boot->tstate == NULL) {
1065 PyMem_DEL(boot);
1066 return PyErr_NoMemory();
1067 }
1068 Py_INCREF(func);
1069 Py_INCREF(args);
1070 Py_XINCREF(keyw);
1071 PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
1072 ident = PyThread_start_new_thread(t_bootstrap, (void*) boot);
1073 if (ident == -1) {
1074 PyErr_SetString(ThreadError, "can't start new thread");
1075 Py_DECREF(func);
1076 Py_DECREF(args);
1077 Py_XDECREF(keyw);
1078 PyThreadState_Clear(boot->tstate);
1079 PyMem_DEL(boot);
1080 return NULL;
1081 }
1082 return PyLong_FromLong(ident);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001083}
1084
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001085PyDoc_STRVAR(start_new_doc,
Andrew M. Kuchling38300c62001-10-05 12:24:15 +00001086"start_new_thread(function, args[, kwargs])\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001087(start_new() is an obsolete synonym)\n\
1088\n\
Guido van Rossum3c288632001-10-16 21:13:49 +00001089Start a new thread and return its identifier. The thread will call the\n\
1090function with positional arguments from the tuple args and keyword arguments\n\
1091taken from the optional dictionary kwargs. The thread exits when the\n\
1092function returns; the return value is ignored. The thread will also exit\n\
1093when the function raises an unhandled exception; a stack trace will be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001094printed unless the exception is SystemExit.\n");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001095
Barry Warsawd0c10421996-12-17 00:05:22 +00001096static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +00001097thread_PyThread_exit_thread(PyObject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyErr_SetNone(PyExc_SystemExit);
1100 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001101}
1102
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001103PyDoc_STRVAR(exit_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001104"exit()\n\
Éric Araujo9bcf8bf2011-05-31 14:08:26 +02001105(exit_thread() is an obsolete synonym)\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001106\n\
1107This is synonymous to ``raise SystemExit''. It will cause the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001108thread to exit silently unless the exception is caught.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001109
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001110static PyObject *
Kurt B. Kaisera1ad5f62003-06-16 18:51:28 +00001111thread_PyThread_interrupt_main(PyObject * self)
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyErr_SetInterrupt();
1114 Py_INCREF(Py_None);
1115 return Py_None;
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001116}
1117
1118PyDoc_STRVAR(interrupt_doc,
1119"interrupt_main()\n\
1120\n\
1121Raise a KeyboardInterrupt in the main thread.\n\
Kurt B. Kaisera1ad5f62003-06-16 18:51:28 +00001122A subthread can use this function to interrupt the main thread."
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001123);
1124
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001125static lockobject *newlockobject(void);
1126
Barry Warsawd0c10421996-12-17 00:05:22 +00001127static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +00001128thread_PyThread_allocate_lock(PyObject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 return (PyObject *) newlockobject();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001131}
1132
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001133PyDoc_STRVAR(allocate_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001134"allocate_lock() -> lock object\n\
1135(allocate() is an obsolete synonym)\n\
1136\n\
Berker Peksag720e6552016-05-02 12:25:35 +03001137Create a new lock object. See help(type(threading.Lock())) for\n\
1138information about locks.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001139
Barry Warsawd0c10421996-12-17 00:05:22 +00001140static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +00001141thread_get_ident(PyObject *self)
Guido van Rossumb6775db1994-08-01 11:34:53 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 long ident;
1144 ident = PyThread_get_thread_ident();
1145 if (ident == -1) {
1146 PyErr_SetString(ThreadError, "no current thread ident");
1147 return NULL;
1148 }
1149 return PyLong_FromLong(ident);
Guido van Rossumb6775db1994-08-01 11:34:53 +00001150}
1151
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001152PyDoc_STRVAR(get_ident_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001153"get_ident() -> integer\n\
1154\n\
1155Return a non-zero integer that uniquely identifies the current thread\n\
1156amongst other threads that exist simultaneously.\n\
1157This may be used to identify per-thread resources.\n\
1158Even though on some platforms threads identities may appear to be\n\
1159allocated consecutive numbers starting at 1, this behavior should not\n\
1160be relied upon, and the number should be seen purely as a magic cookie.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001161A thread's identity may be reused for another thread after it exits.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001162
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001163static PyObject *
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001164thread__count(PyObject *self)
1165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 return PyLong_FromLong(nb_threads);
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001167}
1168
1169PyDoc_STRVAR(_count_doc,
1170"_count() -> integer\n\
1171\n\
Antoine Pitrou9257f5e2009-10-30 22:23:02 +00001172\
1173Return the number of currently running Python threads, excluding \n\
1174the main thread. The returned number comprises all threads created\n\
1175through `start_new_thread()` as well as `threading.Thread`, and not\n\
1176yet finished.\n\
1177\n\
1178This function is meant for internal and specialized purposes only.\n\
1179In most applications `threading.enumerate()` should be used instead.");
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001180
Antoine Pitrou7b476992013-09-07 23:38:37 +02001181static void
1182release_sentinel(void *wr)
1183{
1184 /* Tricky: this function is called when the current thread state
1185 is being deleted. Therefore, only simple C code can safely
1186 execute here. */
1187 PyObject *obj = PyWeakref_GET_OBJECT(wr);
1188 lockobject *lock;
1189 if (obj != Py_None) {
1190 assert(Py_TYPE(obj) == &Locktype);
1191 lock = (lockobject *) obj;
1192 if (lock->locked) {
1193 PyThread_release_lock(lock->lock_lock);
1194 lock->locked = 0;
1195 }
1196 }
1197 /* Deallocating a weakref with a NULL callback only calls
1198 PyObject_GC_Del(), which can't call any Python code. */
1199 Py_DECREF(wr);
1200}
1201
1202static PyObject *
1203thread__set_sentinel(PyObject *self)
1204{
1205 PyObject *wr;
1206 PyThreadState *tstate = PyThreadState_Get();
1207 lockobject *lock;
1208
1209 if (tstate->on_delete_data != NULL) {
1210 /* We must support the re-creation of the lock from a
1211 fork()ed child. */
1212 assert(tstate->on_delete == &release_sentinel);
1213 wr = (PyObject *) tstate->on_delete_data;
1214 tstate->on_delete = NULL;
1215 tstate->on_delete_data = NULL;
1216 Py_DECREF(wr);
1217 }
1218 lock = newlockobject();
1219 if (lock == NULL)
1220 return NULL;
1221 /* The lock is owned by whoever called _set_sentinel(), but the weakref
1222 hangs to the thread state. */
1223 wr = PyWeakref_NewRef((PyObject *) lock, NULL);
1224 if (wr == NULL) {
1225 Py_DECREF(lock);
1226 return NULL;
1227 }
1228 tstate->on_delete_data = (void *) wr;
1229 tstate->on_delete = &release_sentinel;
1230 return (PyObject *) lock;
1231}
1232
1233PyDoc_STRVAR(_set_sentinel_doc,
1234"_set_sentinel() -> lock\n\
1235\n\
1236Set a sentinel lock that will be released when the current thread\n\
1237state is finalized (after it is untied from the interpreter).\n\
1238\n\
1239This is a private API for the threading module.");
1240
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001241static PyObject *
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001242thread_stack_size(PyObject *self, PyObject *args)
1243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 size_t old_size;
1245 Py_ssize_t new_size = 0;
1246 int rc;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size))
1249 return NULL;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 if (new_size < 0) {
1252 PyErr_SetString(PyExc_ValueError,
1253 "size must be 0 or a positive value");
1254 return NULL;
1255 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 old_size = PyThread_get_stacksize();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 rc = PyThread_set_stacksize((size_t) new_size);
1260 if (rc == -1) {
1261 PyErr_Format(PyExc_ValueError,
1262 "size not valid: %zd bytes",
1263 new_size);
1264 return NULL;
1265 }
1266 if (rc == -2) {
1267 PyErr_SetString(ThreadError,
1268 "setting stack size not supported");
1269 return NULL;
1270 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 return PyLong_FromSsize_t((Py_ssize_t) old_size);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001273}
1274
1275PyDoc_STRVAR(stack_size_doc,
1276"stack_size([size]) -> size\n\
1277\n\
1278Return the thread stack size used when creating new threads. The\n\
1279optional size argument specifies the stack size (in bytes) to be used\n\
1280for subsequently created threads, and must be 0 (use platform or\n\
1281configured default) or a positive integer value of at least 32,768 (32k).\n\
1282If changing the thread stack size is unsupported, a ThreadError\n\
1283exception is raised. If the specified size is invalid, a ValueError\n\
1284exception is raised, and the stack size is unmodified. 32k bytes\n\
1285 currently the minimum supported stack size value to guarantee\n\
1286sufficient stack space for the interpreter itself.\n\
1287\n\
1288Note that some platforms may have particular restrictions on values for\n\
1289the stack size, such as requiring a minimum stack size larger than 32kB or\n\
1290requiring allocation in multiples of the system memory page size\n\
1291- platform documentation should be referred to for more information\n\
1292(4kB pages are common; using multiples of 4096 for the stack size is\n\
1293the suggested approach in the absence of more specific information).");
1294
Barry Warsawd0c10421996-12-17 00:05:22 +00001295static PyMethodDef thread_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread,
Victor Stinner754851f2011-04-19 23:58:51 +02001297 METH_VARARGS, start_new_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 {"start_new", (PyCFunction)thread_PyThread_start_new_thread,
Victor Stinner754851f2011-04-19 23:58:51 +02001299 METH_VARARGS, start_new_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock,
1301 METH_NOARGS, allocate_doc},
1302 {"allocate", (PyCFunction)thread_PyThread_allocate_lock,
1303 METH_NOARGS, allocate_doc},
1304 {"exit_thread", (PyCFunction)thread_PyThread_exit_thread,
1305 METH_NOARGS, exit_doc},
1306 {"exit", (PyCFunction)thread_PyThread_exit_thread,
1307 METH_NOARGS, exit_doc},
1308 {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main,
1309 METH_NOARGS, interrupt_doc},
1310 {"get_ident", (PyCFunction)thread_get_ident,
1311 METH_NOARGS, get_ident_doc},
1312 {"_count", (PyCFunction)thread__count,
1313 METH_NOARGS, _count_doc},
1314 {"stack_size", (PyCFunction)thread_stack_size,
Victor Stinner754851f2011-04-19 23:58:51 +02001315 METH_VARARGS, stack_size_doc},
Antoine Pitrou7b476992013-09-07 23:38:37 +02001316 {"_set_sentinel", (PyCFunction)thread__set_sentinel,
1317 METH_NOARGS, _set_sentinel_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 {NULL, NULL} /* sentinel */
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001319};
1320
1321
1322/* Initialization function */
1323
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001324PyDoc_STRVAR(thread_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001325"This module provides primitive operations to write multi-threaded programs.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001326The 'threading' module provides a more convenient interface.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001327
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001328PyDoc_STRVAR(lock_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001329"A lock object is a synchronization primitive. To create a lock,\n\
Berker Peksag720e6552016-05-02 12:25:35 +03001330call threading.Lock(). Methods are:\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001331\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001332acquire() -- lock the lock, possibly blocking until it can be obtained\n\
1333release() -- unlock of the lock\n\
1334locked() -- test whether the lock is currently locked\n\
1335\n\
1336A lock is not owned by the thread that locked it; another thread may\n\
1337unlock it. A thread attempting to lock a lock that it has already locked\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001338will block until another thread unlocks it. Deadlocks may ensue.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001339
Martin v. Löwis1a214512008-06-11 05:26:20 +00001340static struct PyModuleDef threadmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 PyModuleDef_HEAD_INIT,
1342 "_thread",
1343 thread_doc,
1344 -1,
1345 thread_methods,
1346 NULL,
1347 NULL,
1348 NULL,
1349 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001350};
1351
1352
Mark Hammondfe51c6d2002-08-02 02:27:13 +00001353PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00001354PyInit__thread(void)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001355{
Victor Stinnerf5faad22015-03-28 03:52:05 +01001356 PyObject *m, *d, *v;
1357 double time_max;
1358 double timeout_max;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 /* Initialize types: */
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +00001361 if (PyType_Ready(&localdummytype) < 0)
1362 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 if (PyType_Ready(&localtype) < 0)
1364 return NULL;
1365 if (PyType_Ready(&Locktype) < 0)
1366 return NULL;
1367 if (PyType_Ready(&RLocktype) < 0)
1368 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 /* Create the module and add the functions */
1371 m = PyModule_Create(&threadmodule);
1372 if (m == NULL)
1373 return NULL;
Antoine Pitrou7c3e5772010-04-14 15:44:10 +00001374
Victor Stinnerf5faad22015-03-28 03:52:05 +01001375 timeout_max = PY_TIMEOUT_MAX / 1000000;
1376 time_max = floor(_PyTime_AsSecondsDouble(_PyTime_MAX));
1377 timeout_max = Py_MIN(timeout_max, time_max);
1378
1379 v = PyFloat_FromDouble(timeout_max);
1380 if (!v)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 return NULL;
Victor Stinnerf5faad22015-03-28 03:52:05 +01001382 if (PyModule_AddObject(m, "TIMEOUT_MAX", v) < 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001384
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 /* Add a symbolic constant */
1386 d = PyModule_GetDict(m);
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001387 ThreadError = PyExc_RuntimeError;
1388 Py_INCREF(ThreadError);
Victor Stinner754851f2011-04-19 23:58:51 +02001389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 PyDict_SetItemString(d, "error", ThreadError);
1391 Locktype.tp_doc = lock_doc;
1392 Py_INCREF(&Locktype);
1393 PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype);
Antoine Pitrou434736a2009-11-10 18:46:01 +00001394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 Py_INCREF(&RLocktype);
1396 if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0)
1397 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +00001398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 Py_INCREF(&localtype);
1400 if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
1401 return NULL;
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 nb_threads = 0;
1404
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001405 str_dict = PyUnicode_InternFromString("__dict__");
1406 if (str_dict == NULL)
1407 return NULL;
1408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 /* Initialize the C thread library */
1410 PyThread_init_thread();
1411 return m;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001412}