blob: 9925b0e7ec108577180069b177eff62fcaf7c6b2 [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
48 * are returned, depending on whether the lock can be acquired withing the
49 * timeout.
50 */
51static PyLockStatus
52acquire_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds)
53{
54 PyLockStatus r;
55 _PyTime_timeval curtime;
56 _PyTime_timeval endtime;
57
Brett Cannonb94767f2011-02-22 20:15:44 +000058
Antoine Pitrou810023d2010-12-15 22:59:16 +000059 if (microseconds > 0) {
Antoine Pitrou125d5c82011-03-06 08:40:35 +010060 _PyTime_gettimeofday(&endtime);
Antoine Pitrou810023d2010-12-15 22:59:16 +000061 endtime.tv_sec += microseconds / (1000 * 1000);
62 endtime.tv_usec += microseconds % (1000 * 1000);
63 }
64
65
66 do {
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +000067 /* first a simple non-blocking try without releasing the GIL */
68 r = PyThread_acquire_lock_timed(lock, 0, 0);
69 if (r == PY_LOCK_FAILURE && microseconds != 0) {
70 Py_BEGIN_ALLOW_THREADS
71 r = PyThread_acquire_lock_timed(lock, microseconds, 1);
72 Py_END_ALLOW_THREADS
Victor Stinner357f5152013-11-05 15:10:19 +010073 }
Antoine Pitrou810023d2010-12-15 22:59:16 +000074
75 if (r == PY_LOCK_INTR) {
76 /* Run signal handlers if we were interrupted. Propagate
77 * exceptions from signal handlers, such as KeyboardInterrupt, by
78 * passing up PY_LOCK_INTR. */
79 if (Py_MakePendingCalls() < 0) {
80 return PY_LOCK_INTR;
81 }
82
83 /* If we're using a timeout, recompute the timeout after processing
84 * signals, since those can take time. */
Antoine Pitrou125d5c82011-03-06 08:40:35 +010085 if (microseconds > 0) {
Antoine Pitrou810023d2010-12-15 22:59:16 +000086 _PyTime_gettimeofday(&curtime);
87 microseconds = ((endtime.tv_sec - curtime.tv_sec) * 1000000 +
88 (endtime.tv_usec - curtime.tv_usec));
89
90 /* Check for negative values, since those mean block forever.
91 */
92 if (microseconds <= 0) {
93 r = PY_LOCK_FAILURE;
94 }
95 }
96 }
97 } while (r == PY_LOCK_INTR); /* Retry if we were interrupted. */
98
99 return r;
100}
101
Barry Warsawd0c10421996-12-17 00:05:22 +0000102static PyObject *
Antoine Pitrou7c3e5772010-04-14 15:44:10 +0000103lock_PyThread_acquire_lock(lockobject *self, PyObject *args, PyObject *kwds)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 char *kwlist[] = {"blocking", "timeout", NULL};
106 int blocking = 1;
107 double timeout = -1;
108 PY_TIMEOUT_T microseconds;
Antoine Pitrou810023d2010-12-15 22:59:16 +0000109 PyLockStatus r;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000110
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000111 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
112 &blocking, &timeout))
113 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000115 if (!blocking && timeout != -1) {
116 PyErr_SetString(PyExc_ValueError, "can't specify a timeout "
117 "for a non-blocking call");
118 return NULL;
119 }
120 if (timeout < 0 && timeout != -1) {
121 PyErr_SetString(PyExc_ValueError, "timeout value must be "
122 "strictly positive");
123 return NULL;
124 }
125 if (!blocking)
126 microseconds = 0;
127 else if (timeout == -1)
128 microseconds = -1;
129 else {
130 timeout *= 1e6;
131 if (timeout >= (double) PY_TIMEOUT_MAX) {
132 PyErr_SetString(PyExc_OverflowError,
133 "timeout value is too large");
134 return NULL;
135 }
136 microseconds = (PY_TIMEOUT_T) timeout;
137 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000138
Antoine Pitrou810023d2010-12-15 22:59:16 +0000139 r = acquire_timed(self->lock_lock, microseconds);
140 if (r == PY_LOCK_INTR) {
141 return NULL;
142 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000143
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000144 if (r == PY_LOCK_ACQUIRED)
145 self->locked = 1;
Antoine Pitrou810023d2010-12-15 22:59:16 +0000146 return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000147}
148
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000149PyDoc_STRVAR(acquire_doc,
R David Murray95b71102013-02-04 10:15:58 -0500150"acquire([wait]) -> bool\n\
Guido van Rossumf6694362006-03-10 02:28:35 +0000151(acquire_lock() is an obsolete synonym)\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000152\n\
153Lock the lock. Without argument, this blocks if the lock is already\n\
154locked (even by the same thread), waiting for another thread to release\n\
R David Murray95b71102013-02-04 10:15:58 -0500155the lock, and return True once the lock is acquired.\n\
Guido van Rossum8fdc75b2002-04-07 06:32:21 +0000156With an argument, this will only block if the argument is true,\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000157and the return value reflects whether the lock is acquired.\n\
Antoine Pitrou810023d2010-12-15 22:59:16 +0000158The blocking operation is interruptible.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000159
Barry Warsawd0c10421996-12-17 00:05:22 +0000160static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +0000161lock_PyThread_release_lock(lockobject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000162{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 /* Sanity check: the lock must be locked */
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000164 if (!self->locked) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 PyErr_SetString(ThreadError, "release unlocked lock");
166 return NULL;
167 }
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 PyThread_release_lock(self->lock_lock);
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000170 self->locked = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 Py_INCREF(Py_None);
172 return Py_None;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000173}
174
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000175PyDoc_STRVAR(release_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000176"release()\n\
Guido van Rossumf6694362006-03-10 02:28:35 +0000177(release_lock() is an obsolete synonym)\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000178\n\
179Release the lock, allowing another thread that is blocked waiting for\n\
180the lock to acquire the lock. The lock must be in the locked state,\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000181but it needn't be locked by the same thread that unlocks it.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000182
Barry Warsawd0c10421996-12-17 00:05:22 +0000183static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +0000184lock_locked_lock(lockobject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000185{
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000186 return PyBool_FromLong((long)self->locked);
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000187}
188
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000189PyDoc_STRVAR(locked_doc,
Guido van Rossum8fdc75b2002-04-07 06:32:21 +0000190"locked() -> bool\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000191(locked_lock() is an obsolete synonym)\n\
192\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +0000193Return whether the lock is in the locked state.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +0000194
Barry Warsawd0c10421996-12-17 00:05:22 +0000195static PyMethodDef lock_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
197 METH_VARARGS | METH_KEYWORDS, acquire_doc},
198 {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
199 METH_VARARGS | METH_KEYWORDS, acquire_doc},
200 {"release_lock", (PyCFunction)lock_PyThread_release_lock,
201 METH_NOARGS, release_doc},
202 {"release", (PyCFunction)lock_PyThread_release_lock,
203 METH_NOARGS, release_doc},
204 {"locked_lock", (PyCFunction)lock_locked_lock,
205 METH_NOARGS, locked_doc},
206 {"locked", (PyCFunction)lock_locked_lock,
207 METH_NOARGS, locked_doc},
208 {"__enter__", (PyCFunction)lock_PyThread_acquire_lock,
209 METH_VARARGS | METH_KEYWORDS, acquire_doc},
210 {"__exit__", (PyCFunction)lock_PyThread_release_lock,
211 METH_VARARGS, release_doc},
212 {NULL, NULL} /* sentinel */
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000213};
214
Barry Warsawd0c10421996-12-17 00:05:22 +0000215static PyTypeObject Locktype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000216 PyVarObject_HEAD_INIT(&PyType_Type, 0)
217 "_thread.lock", /*tp_name*/
218 sizeof(lockobject), /*tp_size*/
219 0, /*tp_itemsize*/
220 /* methods */
221 (destructor)lock_dealloc, /*tp_dealloc*/
222 0, /*tp_print*/
223 0, /*tp_getattr*/
224 0, /*tp_setattr*/
225 0, /*tp_reserved*/
226 0, /*tp_repr*/
227 0, /*tp_as_number*/
228 0, /*tp_as_sequence*/
229 0, /*tp_as_mapping*/
230 0, /*tp_hash*/
231 0, /*tp_call*/
232 0, /*tp_str*/
233 0, /*tp_getattro*/
234 0, /*tp_setattro*/
235 0, /*tp_as_buffer*/
236 Py_TPFLAGS_DEFAULT, /*tp_flags*/
237 0, /*tp_doc*/
238 0, /*tp_traverse*/
239 0, /*tp_clear*/
240 0, /*tp_richcompare*/
241 offsetof(lockobject, in_weakreflist), /*tp_weaklistoffset*/
242 0, /*tp_iter*/
243 0, /*tp_iternext*/
244 lock_methods, /*tp_methods*/
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000245};
246
Antoine Pitrou434736a2009-11-10 18:46:01 +0000247/* Recursive lock objects */
248
249typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000250 PyObject_HEAD
251 PyThread_type_lock rlock_lock;
252 long rlock_owner;
253 unsigned long rlock_count;
254 PyObject *in_weakreflist;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000255} rlockobject;
256
257static void
258rlock_dealloc(rlockobject *self)
259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 if (self->in_weakreflist != NULL)
261 PyObject_ClearWeakRefs((PyObject *) self);
Victor Stinner357f5152013-11-05 15:10:19 +0100262 /* self->rlock_lock can be NULL if PyThread_allocate_lock() failed
263 in rlock_new() */
264 if (self->rlock_lock != NULL) {
265 /* Unlock the lock so it's safe to free it */
266 if (self->rlock_count > 0)
267 PyThread_release_lock(self->rlock_lock);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268
Victor Stinner357f5152013-11-05 15:10:19 +0100269 PyThread_free_lock(self->rlock_lock);
270 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 Py_TYPE(self)->tp_free(self);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000272}
273
274static PyObject *
275rlock_acquire(rlockobject *self, PyObject *args, PyObject *kwds)
276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 char *kwlist[] = {"blocking", "timeout", NULL};
278 int blocking = 1;
279 double timeout = -1;
280 PY_TIMEOUT_T microseconds;
281 long tid;
Antoine Pitrou810023d2010-12-15 22:59:16 +0000282 PyLockStatus r = PY_LOCK_ACQUIRED;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
285 &blocking, &timeout))
286 return NULL;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000288 if (!blocking && timeout != -1) {
289 PyErr_SetString(PyExc_ValueError, "can't specify a timeout "
290 "for a non-blocking call");
291 return NULL;
292 }
293 if (timeout < 0 && timeout != -1) {
294 PyErr_SetString(PyExc_ValueError, "timeout value must be "
295 "strictly positive");
296 return NULL;
297 }
298 if (!blocking)
299 microseconds = 0;
300 else if (timeout == -1)
301 microseconds = -1;
302 else {
303 timeout *= 1e6;
304 if (timeout >= (double) PY_TIMEOUT_MAX) {
305 PyErr_SetString(PyExc_OverflowError,
306 "timeout value is too large");
307 return NULL;
308 }
309 microseconds = (PY_TIMEOUT_T) timeout;
310 }
Antoine Pitrou434736a2009-11-10 18:46:01 +0000311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 tid = PyThread_get_thread_ident();
313 if (self->rlock_count > 0 && tid == self->rlock_owner) {
314 unsigned long count = self->rlock_count + 1;
315 if (count <= self->rlock_count) {
316 PyErr_SetString(PyExc_OverflowError,
317 "Internal lock count overflowed");
318 return NULL;
319 }
320 self->rlock_count = count;
321 Py_RETURN_TRUE;
322 }
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000323 r = acquire_timed(self->rlock_lock, microseconds);
Antoine Pitrou810023d2010-12-15 22:59:16 +0000324 if (r == PY_LOCK_ACQUIRED) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 assert(self->rlock_count == 0);
326 self->rlock_owner = tid;
327 self->rlock_count = 1;
328 }
Antoine Pitrou810023d2010-12-15 22:59:16 +0000329 else if (r == PY_LOCK_INTR) {
330 return NULL;
331 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000332
Antoine Pitrou810023d2010-12-15 22:59:16 +0000333 return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000334}
335
336PyDoc_STRVAR(rlock_acquire_doc,
337"acquire(blocking=True) -> bool\n\
338\n\
339Lock the lock. `blocking` indicates whether we should wait\n\
340for the lock to be available or not. If `blocking` is False\n\
341and another thread holds the lock, the method will return False\n\
342immediately. If `blocking` is True and another thread holds\n\
343the lock, the method will wait for the lock to be released,\n\
344take it and then return True.\n\
Antoine Pitrou810023d2010-12-15 22:59:16 +0000345(note: the blocking operation is interruptible.)\n\
Antoine Pitrou434736a2009-11-10 18:46:01 +0000346\n\
347In all other cases, the method will return True immediately.\n\
348Precisely, if the current thread already holds the lock, its\n\
349internal counter is simply incremented. If nobody holds the lock,\n\
350the lock is taken and its internal counter initialized to 1.");
351
352static PyObject *
353rlock_release(rlockobject *self)
354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 long tid = PyThread_get_thread_ident();
Antoine Pitrou434736a2009-11-10 18:46:01 +0000356
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 if (self->rlock_count == 0 || self->rlock_owner != tid) {
358 PyErr_SetString(PyExc_RuntimeError,
359 "cannot release un-acquired lock");
360 return NULL;
361 }
362 if (--self->rlock_count == 0) {
363 self->rlock_owner = 0;
364 PyThread_release_lock(self->rlock_lock);
365 }
366 Py_RETURN_NONE;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000367}
368
369PyDoc_STRVAR(rlock_release_doc,
370"release()\n\
371\n\
372Release the lock, allowing another thread that is blocked waiting for\n\
373the lock to acquire the lock. The lock must be in the locked state,\n\
374and must be locked by the same thread that unlocks it; otherwise a\n\
375`RuntimeError` is raised.\n\
376\n\
377Do note that if the lock was acquire()d several times in a row by the\n\
378current thread, release() needs to be called as many times for the lock\n\
379to be available for other threads.");
380
381static PyObject *
Victor Stinnere8794522014-01-02 12:47:24 +0100382rlock_acquire_restore(rlockobject *self, PyObject *args)
Antoine Pitrou434736a2009-11-10 18:46:01 +0000383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 long owner;
385 unsigned long count;
386 int r = 1;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000387
Victor Stinnere8794522014-01-02 12:47:24 +0100388 if (!PyArg_ParseTuple(args, "(kl):_acquire_restore", &count, &owner))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return NULL;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 if (!PyThread_acquire_lock(self->rlock_lock, 0)) {
392 Py_BEGIN_ALLOW_THREADS
393 r = PyThread_acquire_lock(self->rlock_lock, 1);
394 Py_END_ALLOW_THREADS
395 }
396 if (!r) {
397 PyErr_SetString(ThreadError, "couldn't acquire lock");
398 return NULL;
399 }
400 assert(self->rlock_count == 0);
401 self->rlock_owner = owner;
402 self->rlock_count = count;
403 Py_RETURN_NONE;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000404}
405
406PyDoc_STRVAR(rlock_acquire_restore_doc,
407"_acquire_restore(state) -> None\n\
408\n\
409For internal use by `threading.Condition`.");
410
411static PyObject *
412rlock_release_save(rlockobject *self)
413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 long owner;
415 unsigned long count;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000416
Victor Stinnerc2824d42011-04-24 23:41:33 +0200417 if (self->rlock_count == 0) {
418 PyErr_SetString(PyExc_RuntimeError,
419 "cannot release un-acquired lock");
420 return NULL;
421 }
422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 owner = self->rlock_owner;
424 count = self->rlock_count;
425 self->rlock_count = 0;
426 self->rlock_owner = 0;
427 PyThread_release_lock(self->rlock_lock);
428 return Py_BuildValue("kl", count, owner);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000429}
430
431PyDoc_STRVAR(rlock_release_save_doc,
432"_release_save() -> tuple\n\
433\n\
434For internal use by `threading.Condition`.");
435
436
437static PyObject *
438rlock_is_owned(rlockobject *self)
439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 long tid = PyThread_get_thread_ident();
441
442 if (self->rlock_count > 0 && self->rlock_owner == tid) {
443 Py_RETURN_TRUE;
444 }
445 Py_RETURN_FALSE;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000446}
447
448PyDoc_STRVAR(rlock_is_owned_doc,
449"_is_owned() -> bool\n\
450\n\
451For internal use by `threading.Condition`.");
452
453static PyObject *
454rlock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 rlockobject *self;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 self = (rlockobject *) type->tp_alloc(type, 0);
459 if (self != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 self->in_weakreflist = NULL;
461 self->rlock_owner = 0;
462 self->rlock_count = 0;
Victor Stinner357f5152013-11-05 15:10:19 +0100463
464 self->rlock_lock = PyThread_allocate_lock();
465 if (self->rlock_lock == NULL) {
466 Py_DECREF(self);
467 PyErr_SetString(ThreadError, "can't allocate lock");
468 return NULL;
469 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 }
Antoine Pitrou434736a2009-11-10 18:46:01 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 return (PyObject *) self;
Antoine Pitrou434736a2009-11-10 18:46:01 +0000473}
474
475static PyObject *
476rlock_repr(rlockobject *self)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 return PyUnicode_FromFormat("<%s owner=%ld count=%lu>",
479 Py_TYPE(self)->tp_name, self->rlock_owner, self->rlock_count);
Antoine Pitrou434736a2009-11-10 18:46:01 +0000480}
481
482
483static PyMethodDef rlock_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 {"acquire", (PyCFunction)rlock_acquire,
485 METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
486 {"release", (PyCFunction)rlock_release,
487 METH_NOARGS, rlock_release_doc},
488 {"_is_owned", (PyCFunction)rlock_is_owned,
489 METH_NOARGS, rlock_is_owned_doc},
490 {"_acquire_restore", (PyCFunction)rlock_acquire_restore,
Victor Stinnere8794522014-01-02 12:47:24 +0100491 METH_VARARGS, rlock_acquire_restore_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 {"_release_save", (PyCFunction)rlock_release_save,
493 METH_NOARGS, rlock_release_save_doc},
494 {"__enter__", (PyCFunction)rlock_acquire,
495 METH_VARARGS | METH_KEYWORDS, rlock_acquire_doc},
496 {"__exit__", (PyCFunction)rlock_release,
497 METH_VARARGS, rlock_release_doc},
498 {NULL, NULL} /* sentinel */
Antoine Pitrou434736a2009-11-10 18:46:01 +0000499};
500
501
502static PyTypeObject RLocktype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 PyVarObject_HEAD_INIT(&PyType_Type, 0)
504 "_thread.RLock", /*tp_name*/
505 sizeof(rlockobject), /*tp_size*/
506 0, /*tp_itemsize*/
507 /* methods */
508 (destructor)rlock_dealloc, /*tp_dealloc*/
509 0, /*tp_print*/
510 0, /*tp_getattr*/
511 0, /*tp_setattr*/
512 0, /*tp_reserved*/
513 (reprfunc)rlock_repr, /*tp_repr*/
514 0, /*tp_as_number*/
515 0, /*tp_as_sequence*/
516 0, /*tp_as_mapping*/
517 0, /*tp_hash*/
518 0, /*tp_call*/
519 0, /*tp_str*/
520 0, /*tp_getattro*/
521 0, /*tp_setattro*/
522 0, /*tp_as_buffer*/
523 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
524 0, /*tp_doc*/
525 0, /*tp_traverse*/
526 0, /*tp_clear*/
527 0, /*tp_richcompare*/
528 offsetof(rlockobject, in_weakreflist), /*tp_weaklistoffset*/
529 0, /*tp_iter*/
530 0, /*tp_iternext*/
531 rlock_methods, /*tp_methods*/
532 0, /* tp_members */
533 0, /* tp_getset */
534 0, /* tp_base */
535 0, /* tp_dict */
536 0, /* tp_descr_get */
537 0, /* tp_descr_set */
538 0, /* tp_dictoffset */
539 0, /* tp_init */
540 PyType_GenericAlloc, /* tp_alloc */
541 rlock_new /* tp_new */
Antoine Pitrou434736a2009-11-10 18:46:01 +0000542};
543
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000544static lockobject *
545newlockobject(void)
546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 lockobject *self;
548 self = PyObject_New(lockobject, &Locktype);
549 if (self == NULL)
550 return NULL;
551 self->lock_lock = PyThread_allocate_lock();
Kristjan Valur Jonsson69cf9132012-06-22 18:40:02 +0000552 self->locked = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 self->in_weakreflist = NULL;
554 if (self->lock_lock == NULL) {
555 Py_DECREF(self);
556 PyErr_SetString(ThreadError, "can't allocate lock");
557 return NULL;
558 }
559 return self;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000560}
561
Jim Fultond15dc062004-07-14 19:11:50 +0000562/* Thread-local objects */
563
564#include "structmember.h"
565
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000566/* Quick overview:
567
568 We need to be able to reclaim reference cycles as soon as possible
569 (both when a thread is being terminated, or a thread-local object
570 becomes unreachable from user data). Constraints:
571 - it must not be possible for thread-state dicts to be involved in
572 reference cycles (otherwise the cyclic GC will refuse to consider
573 objects referenced from a reachable thread-state dict, even though
574 local_dealloc would clear them)
575 - the death of a thread-state dict must still imply destruction of the
576 corresponding local dicts in all thread-local objects.
577
578 Our implementation uses small "localdummy" objects in order to break
579 the reference chain. These trivial objects are hashable (using the
580 default scheme of identity hashing) and weakrefable.
581 Each thread-state holds a separate localdummy for each local object
582 (as a /strong reference/),
583 and each thread-local object holds a dict mapping /weak references/
584 of localdummies to local dicts.
585
586 Therefore:
587 - only the thread-state dict holds a strong reference to the dummies
588 - only the thread-local object holds a strong reference to the local dicts
589 - only outside objects (application- or library-level) hold strong
590 references to the thread-local objects
591 - as soon as a thread-state dict is destroyed, the weakref callbacks of all
592 dummies attached to that thread are called, and destroy the corresponding
593 local dicts from thread-local objects
594 - as soon as a thread-local object is destroyed, its local dicts are
595 destroyed and its dummies are manually removed from all thread states
596 - the GC can do its work correctly when a thread-local object is dangling,
597 without any interference from the thread-state dicts
598
599 As an additional optimization, each localdummy holds a borrowed reference
600 to the corresponding localdict. This borrowed reference is only used
601 by the thread-local object which has created the localdummy, which should
602 guarantee that the localdict still exists when accessed.
603*/
604
605typedef struct {
606 PyObject_HEAD
607 PyObject *localdict; /* Borrowed reference! */
608 PyObject *weakreflist; /* List of weak references to self */
609} localdummyobject;
610
611static void
612localdummy_dealloc(localdummyobject *self)
613{
614 if (self->weakreflist != NULL)
615 PyObject_ClearWeakRefs((PyObject *) self);
616 Py_TYPE(self)->tp_free((PyObject*)self);
617}
618
619static PyTypeObject localdummytype = {
620 PyVarObject_HEAD_INIT(NULL, 0)
621 /* tp_name */ "_thread._localdummy",
622 /* tp_basicsize */ sizeof(localdummyobject),
623 /* tp_itemsize */ 0,
624 /* tp_dealloc */ (destructor)localdummy_dealloc,
625 /* tp_print */ 0,
626 /* tp_getattr */ 0,
627 /* tp_setattr */ 0,
628 /* tp_reserved */ 0,
629 /* tp_repr */ 0,
630 /* tp_as_number */ 0,
631 /* tp_as_sequence */ 0,
632 /* tp_as_mapping */ 0,
633 /* tp_hash */ 0,
634 /* tp_call */ 0,
635 /* tp_str */ 0,
636 /* tp_getattro */ 0,
637 /* tp_setattro */ 0,
638 /* tp_as_buffer */ 0,
639 /* tp_flags */ Py_TPFLAGS_DEFAULT,
640 /* tp_doc */ "Thread-local dummy",
641 /* tp_traverse */ 0,
642 /* tp_clear */ 0,
643 /* tp_richcompare */ 0,
644 /* tp_weaklistoffset */ offsetof(localdummyobject, weakreflist)
645};
646
647
Jim Fultond15dc062004-07-14 19:11:50 +0000648typedef struct {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyObject_HEAD
650 PyObject *key;
651 PyObject *args;
652 PyObject *kw;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000653 PyObject *weakreflist; /* List of weak references to self */
654 /* A {localdummy weakref -> localdict} dict */
655 PyObject *dummies;
656 /* The callback for weakrefs to localdummies */
657 PyObject *wr_callback;
Jim Fultond15dc062004-07-14 19:11:50 +0000658} localobject;
659
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000660/* Forward declaration */
661static PyObject *_ldict(localobject *self);
662static PyObject *_localdummy_destroyed(PyObject *meth_self, PyObject *dummyweakref);
663
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000664/* Create and register the dummy for the current thread.
665 Returns a borrowed reference of the corresponding local dict */
666static PyObject *
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000667_local_create_dummy(localobject *self)
668{
669 PyObject *tdict, *ldict = NULL, *wr = NULL;
670 localdummyobject *dummy = NULL;
671 int r;
672
673 tdict = PyThreadState_GetDict();
674 if (tdict == NULL) {
675 PyErr_SetString(PyExc_SystemError,
676 "Couldn't get thread-state dictionary");
677 goto err;
678 }
679
680 ldict = PyDict_New();
681 if (ldict == NULL)
682 goto err;
683 dummy = (localdummyobject *) localdummytype.tp_alloc(&localdummytype, 0);
684 if (dummy == NULL)
685 goto err;
686 dummy->localdict = ldict;
687 wr = PyWeakref_NewRef((PyObject *) dummy, self->wr_callback);
688 if (wr == NULL)
689 goto err;
690
691 /* As a side-effect, this will cache the weakref's hash before the
692 dummy gets deleted */
693 r = PyDict_SetItem(self->dummies, wr, ldict);
694 if (r < 0)
695 goto err;
696 Py_CLEAR(wr);
697 r = PyDict_SetItem(tdict, self->key, (PyObject *) dummy);
698 if (r < 0)
699 goto err;
700 Py_CLEAR(dummy);
701
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000702 Py_DECREF(ldict);
703 return ldict;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000704
705err:
706 Py_XDECREF(ldict);
707 Py_XDECREF(wr);
708 Py_XDECREF(dummy);
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000709 return NULL;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000710}
711
Jim Fultond15dc062004-07-14 19:11:50 +0000712static PyObject *
713local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
714{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 localobject *self;
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000716 PyObject *wr;
717 static PyMethodDef wr_callback_def = {
718 "_localdummy_destroyed", (PyCFunction) _localdummy_destroyed, METH_O
719 };
Jim Fultond15dc062004-07-14 19:11:50 +0000720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (type->tp_init == PyBaseObject_Type.tp_init
722 && ((args && PyObject_IsTrue(args))
723 || (kw && PyObject_IsTrue(kw)))) {
724 PyErr_SetString(PyExc_TypeError,
725 "Initialization arguments are not supported");
726 return NULL;
727 }
Jim Fultond15dc062004-07-14 19:11:50 +0000728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 self = (localobject *)type->tp_alloc(type, 0);
730 if (self == NULL)
731 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +0000732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 Py_XINCREF(args);
734 self->args = args;
735 Py_XINCREF(kw);
736 self->kw = kw;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 self->key = PyUnicode_FromFormat("thread.local.%p", self);
738 if (self->key == NULL)
739 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000740
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000741 self->dummies = PyDict_New();
742 if (self->dummies == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000743 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000744
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000745 /* We use a weak reference to self in the callback closure
746 in order to avoid spurious reference cycles */
747 wr = PyWeakref_NewRef((PyObject *) self, NULL);
748 if (wr == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000749 goto err;
Andrew Svetlov3ba3a3e2012-12-25 13:32:35 +0200750 self->wr_callback = PyCFunction_NewEx(&wr_callback_def, wr, NULL);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000751 Py_DECREF(wr);
752 if (self->wr_callback == NULL)
753 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000754
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000755 if (_local_create_dummy(self) == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756 goto err;
Jim Fultond15dc062004-07-14 19:11:50 +0000757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 return (PyObject *)self;
Michael W. Hudson2368b3c2005-06-15 12:48:40 +0000759
760 err:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 Py_DECREF(self);
762 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +0000763}
764
765static int
766local_traverse(localobject *self, visitproc visit, void *arg)
767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 Py_VISIT(self->args);
769 Py_VISIT(self->kw);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000770 Py_VISIT(self->dummies);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000771 return 0;
Jim Fultond15dc062004-07-14 19:11:50 +0000772}
773
774static int
775local_clear(localobject *self)
776{
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000777 PyThreadState *tstate;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 Py_CLEAR(self->args);
779 Py_CLEAR(self->kw);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000780 Py_CLEAR(self->dummies);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000781 Py_CLEAR(self->wr_callback);
782 /* Remove all strong references to dummies from the thread states */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (self->key
784 && (tstate = PyThreadState_Get())
785 && tstate->interp) {
786 for(tstate = PyInterpreterState_ThreadHead(tstate->interp);
787 tstate;
788 tstate = PyThreadState_Next(tstate))
789 if (tstate->dict &&
790 PyDict_GetItem(tstate->dict, self->key))
791 PyDict_DelItem(tstate->dict, self->key);
792 }
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000793 return 0;
794}
Jim Fultond15dc062004-07-14 19:11:50 +0000795
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000796static void
797local_dealloc(localobject *self)
798{
799 /* Weakrefs must be invalidated right now, otherwise they can be used
800 from code called below, which is very dangerous since Py_REFCNT(self) == 0 */
801 if (self->weakreflist != NULL)
802 PyObject_ClearWeakRefs((PyObject *) self);
803
804 PyObject_GC_UnTrack(self);
805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 local_clear(self);
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000807 Py_XDECREF(self->key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 Py_TYPE(self)->tp_free((PyObject*)self);
Jim Fultond15dc062004-07-14 19:11:50 +0000809}
810
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000811/* Returns a borrowed reference to the local dict, creating it if necessary */
Jim Fultond15dc062004-07-14 19:11:50 +0000812static PyObject *
813_ldict(localobject *self)
814{
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000815 PyObject *tdict, *ldict, *dummy;
Jim Fultond15dc062004-07-14 19:11:50 +0000816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 tdict = PyThreadState_GetDict();
818 if (tdict == NULL) {
819 PyErr_SetString(PyExc_SystemError,
820 "Couldn't get thread-state dictionary");
821 return NULL;
822 }
Jim Fultond15dc062004-07-14 19:11:50 +0000823
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000824 dummy = PyDict_GetItem(tdict, self->key);
825 if (dummy == NULL) {
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000826 ldict = _local_create_dummy(self);
827 if (ldict == NULL)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init &&
831 Py_TYPE(self)->tp_init((PyObject*)self,
832 self->args, self->kw) < 0) {
833 /* we need to get rid of ldict from thread so
834 we create a new one the next time we do an attr
Ezio Melotti42da6632011-03-15 05:18:48 +0200835 access */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyDict_DelItem(tdict, self->key);
837 return NULL;
838 }
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000839 }
840 else {
841 assert(Py_TYPE(dummy) == &localdummytype);
842 ldict = ((localdummyobject *) dummy)->localdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 }
Jim Fultond15dc062004-07-14 19:11:50 +0000844
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000845 return ldict;
Jim Fultond15dc062004-07-14 19:11:50 +0000846}
847
Jim Fultond15dc062004-07-14 19:11:50 +0000848static int
849local_setattro(localobject *self, PyObject *name, PyObject *v)
850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851 PyObject *ldict;
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000852 int r;
Jim Fultond15dc062004-07-14 19:11:50 +0000853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 ldict = _ldict(self);
855 if (ldict == NULL)
856 return -1;
857
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000858 r = PyObject_RichCompareBool(name, str_dict, Py_EQ);
859 if (r == 1) {
860 PyErr_Format(PyExc_AttributeError,
861 "'%.50s' object attribute '%U' is read-only",
862 Py_TYPE(self)->tp_name, name);
863 return -1;
864 }
865 if (r == -1)
866 return -1;
Jim Fultond15dc062004-07-14 19:11:50 +0000867
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000868 return _PyObject_GenericSetAttrWithDict((PyObject *)self, name, v, ldict);
Jim Fultond15dc062004-07-14 19:11:50 +0000869}
870
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000871static PyObject *local_getattro(localobject *, PyObject *);
872
Jim Fultond15dc062004-07-14 19:11:50 +0000873static PyTypeObject localtype = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 PyVarObject_HEAD_INIT(NULL, 0)
875 /* tp_name */ "_thread._local",
876 /* tp_basicsize */ sizeof(localobject),
877 /* tp_itemsize */ 0,
878 /* tp_dealloc */ (destructor)local_dealloc,
879 /* tp_print */ 0,
880 /* tp_getattr */ 0,
881 /* tp_setattr */ 0,
882 /* tp_reserved */ 0,
883 /* tp_repr */ 0,
884 /* tp_as_number */ 0,
885 /* tp_as_sequence */ 0,
886 /* tp_as_mapping */ 0,
887 /* tp_hash */ 0,
888 /* tp_call */ 0,
889 /* tp_str */ 0,
890 /* tp_getattro */ (getattrofunc)local_getattro,
891 /* tp_setattro */ (setattrofunc)local_setattro,
892 /* tp_as_buffer */ 0,
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000893 /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
894 | Py_TPFLAGS_HAVE_GC,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 /* tp_doc */ "Thread-local data",
896 /* tp_traverse */ (traverseproc)local_traverse,
897 /* tp_clear */ (inquiry)local_clear,
898 /* tp_richcompare */ 0,
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000899 /* tp_weaklistoffset */ offsetof(localobject, weakreflist),
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 /* tp_iter */ 0,
901 /* tp_iternext */ 0,
902 /* tp_methods */ 0,
903 /* tp_members */ 0,
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000904 /* tp_getset */ 0,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 /* tp_base */ 0,
906 /* tp_dict */ 0, /* internal use */
907 /* tp_descr_get */ 0,
908 /* tp_descr_set */ 0,
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000909 /* tp_dictoffset */ 0,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 /* tp_init */ 0,
911 /* tp_alloc */ 0,
912 /* tp_new */ local_new,
913 /* tp_free */ 0, /* Low-level free-mem routine */
914 /* tp_is_gc */ 0, /* For PyObject_IS_GC */
Jim Fultond15dc062004-07-14 19:11:50 +0000915};
916
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000917static PyObject *
918local_getattro(localobject *self, PyObject *name)
919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 PyObject *ldict, *value;
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000921 int r;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000922
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 ldict = _ldict(self);
924 if (ldict == NULL)
925 return NULL;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000926
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000927 r = PyObject_RichCompareBool(name, str_dict, Py_EQ);
928 if (r == 1) {
929 Py_INCREF(ldict);
930 return ldict;
931 }
932 if (r == -1)
933 return NULL;
934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 if (Py_TYPE(self) != &localtype)
936 /* use generic lookup for subtypes */
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000937 return _PyObject_GenericGetAttrWithDict((PyObject *)self, name, ldict);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 /* Optimization: just look in dict ourselves */
940 value = PyDict_GetItem(ldict, name);
941 if (value == NULL)
942 /* Fall back on generic to get __class__ and __dict__ */
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000943 return _PyObject_GenericGetAttrWithDict((PyObject *)self, name, ldict);
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 Py_INCREF(value);
946 return value;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000947}
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000948
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000949/* Called when a dummy is destroyed. */
950static PyObject *
951_localdummy_destroyed(PyObject *localweakref, PyObject *dummyweakref)
952{
953 PyObject *obj;
954 localobject *self;
955 assert(PyWeakref_CheckRef(localweakref));
956 obj = PyWeakref_GET_OBJECT(localweakref);
957 if (obj == Py_None)
958 Py_RETURN_NONE;
959 Py_INCREF(obj);
960 assert(PyObject_TypeCheck(obj, &localtype));
961 /* If the thread-local object is still alive and not being cleared,
962 remove the corresponding local dict */
963 self = (localobject *) obj;
964 if (self->dummies != NULL) {
965 PyObject *ldict;
966 ldict = PyDict_GetItem(self->dummies, dummyweakref);
967 if (ldict != NULL) {
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +0000968 PyDict_DelItem(self->dummies, dummyweakref);
969 }
970 if (PyErr_Occurred())
971 PyErr_WriteUnraisable(obj);
972 }
973 Py_DECREF(obj);
974 Py_RETURN_NONE;
975}
976
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000977/* Module functions */
978
Guido van Rossuma027efa1997-05-05 20:56:21 +0000979struct bootstate {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 PyInterpreterState *interp;
981 PyObject *func;
982 PyObject *args;
983 PyObject *keyw;
984 PyThreadState *tstate;
Guido van Rossuma027efa1997-05-05 20:56:21 +0000985};
986
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000987static void
Peter Schneider-Kamp3707efe2000-07-10 10:03:58 +0000988t_bootstrap(void *boot_raw)
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 struct bootstate *boot = (struct bootstate *) boot_raw;
991 PyThreadState *tstate;
992 PyObject *res;
Guido van Rossum1984f1e1992-08-04 12:41:02 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 tstate = boot->tstate;
995 tstate->thread_id = PyThread_get_thread_ident();
996 _PyThreadState_Init(tstate);
997 PyEval_AcquireThread(tstate);
998 nb_threads++;
999 res = PyEval_CallObjectWithKeywords(
1000 boot->func, boot->args, boot->keyw);
1001 if (res == NULL) {
1002 if (PyErr_ExceptionMatches(PyExc_SystemExit))
1003 PyErr_Clear();
1004 else {
1005 PyObject *file;
Benjamin Petersone9000962012-04-02 11:15:17 -04001006 PyObject *exc, *value, *tb;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 PySys_WriteStderr(
1008 "Unhandled exception in thread started by ");
Benjamin Petersone9000962012-04-02 11:15:17 -04001009 PyErr_Fetch(&exc, &value, &tb);
Victor Stinnerbd303c12013-11-07 23:07:29 +01001010 file = _PySys_GetObjectId(&PyId_stderr);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 if (file != NULL && file != Py_None)
1012 PyFile_WriteObject(boot->func, file, 0);
1013 else
1014 PyObject_Print(boot->func, stderr, 0);
1015 PySys_WriteStderr("\n");
Benjamin Petersone9000962012-04-02 11:15:17 -04001016 PyErr_Restore(exc, value, tb);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyErr_PrintEx(0);
1018 }
1019 }
1020 else
1021 Py_DECREF(res);
1022 Py_DECREF(boot->func);
1023 Py_DECREF(boot->args);
1024 Py_XDECREF(boot->keyw);
1025 PyMem_DEL(boot_raw);
1026 nb_threads--;
1027 PyThreadState_Clear(tstate);
1028 PyThreadState_DeleteCurrent();
1029 PyThread_exit_thread();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001030}
1031
Barry Warsawd0c10421996-12-17 00:05:22 +00001032static PyObject *
Peter Schneider-Kamp3707efe2000-07-10 10:03:58 +00001033thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyObject *func, *args, *keyw = NULL;
1036 struct bootstate *boot;
1037 long ident;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3,
1040 &func, &args, &keyw))
1041 return NULL;
1042 if (!PyCallable_Check(func)) {
1043 PyErr_SetString(PyExc_TypeError,
1044 "first arg must be callable");
1045 return NULL;
1046 }
1047 if (!PyTuple_Check(args)) {
1048 PyErr_SetString(PyExc_TypeError,
1049 "2nd arg must be a tuple");
1050 return NULL;
1051 }
1052 if (keyw != NULL && !PyDict_Check(keyw)) {
1053 PyErr_SetString(PyExc_TypeError,
1054 "optional 3rd arg must be a dictionary");
1055 return NULL;
1056 }
1057 boot = PyMem_NEW(struct bootstate, 1);
1058 if (boot == NULL)
1059 return PyErr_NoMemory();
1060 boot->interp = PyThreadState_GET()->interp;
1061 boot->func = func;
1062 boot->args = args;
1063 boot->keyw = keyw;
1064 boot->tstate = _PyThreadState_Prealloc(boot->interp);
1065 if (boot->tstate == NULL) {
1066 PyMem_DEL(boot);
1067 return PyErr_NoMemory();
1068 }
1069 Py_INCREF(func);
1070 Py_INCREF(args);
1071 Py_XINCREF(keyw);
1072 PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
1073 ident = PyThread_start_new_thread(t_bootstrap, (void*) boot);
1074 if (ident == -1) {
1075 PyErr_SetString(ThreadError, "can't start new thread");
1076 Py_DECREF(func);
1077 Py_DECREF(args);
1078 Py_XDECREF(keyw);
1079 PyThreadState_Clear(boot->tstate);
1080 PyMem_DEL(boot);
1081 return NULL;
1082 }
1083 return PyLong_FromLong(ident);
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001084}
1085
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001086PyDoc_STRVAR(start_new_doc,
Andrew M. Kuchling38300c62001-10-05 12:24:15 +00001087"start_new_thread(function, args[, kwargs])\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001088(start_new() is an obsolete synonym)\n\
1089\n\
Guido van Rossum3c288632001-10-16 21:13:49 +00001090Start a new thread and return its identifier. The thread will call the\n\
1091function with positional arguments from the tuple args and keyword arguments\n\
1092taken from the optional dictionary kwargs. The thread exits when the\n\
1093function returns; the return value is ignored. The thread will also exit\n\
1094when the function raises an unhandled exception; a stack trace will be\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001095printed unless the exception is SystemExit.\n");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001096
Barry Warsawd0c10421996-12-17 00:05:22 +00001097static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +00001098thread_PyThread_exit_thread(PyObject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 PyErr_SetNone(PyExc_SystemExit);
1101 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001102}
1103
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001104PyDoc_STRVAR(exit_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001105"exit()\n\
Éric Araujo9bcf8bf2011-05-31 14:08:26 +02001106(exit_thread() is an obsolete synonym)\n\
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001107\n\
1108This is synonymous to ``raise SystemExit''. It will cause the current\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001109thread to exit silently unless the exception is caught.");
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001110
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001111static PyObject *
Kurt B. Kaisera1ad5f62003-06-16 18:51:28 +00001112thread_PyThread_interrupt_main(PyObject * self)
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001113{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyErr_SetInterrupt();
1115 Py_INCREF(Py_None);
1116 return Py_None;
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001117}
1118
1119PyDoc_STRVAR(interrupt_doc,
1120"interrupt_main()\n\
1121\n\
1122Raise a KeyboardInterrupt in the main thread.\n\
Kurt B. Kaisera1ad5f62003-06-16 18:51:28 +00001123A subthread can use this function to interrupt the main thread."
Kurt B. Kaisera11e8462003-06-13 21:59:45 +00001124);
1125
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001126static lockobject *newlockobject(void);
1127
Barry Warsawd0c10421996-12-17 00:05:22 +00001128static PyObject *
Neal Norwitz3a6f9782002-03-25 20:46:46 +00001129thread_PyThread_allocate_lock(PyObject *self)
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001130{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 return (PyObject *) newlockobject();
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001132}
1133
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00001134PyDoc_STRVAR(allocate_doc,
Guido van Rossum75e9fc31998-06-27 18:21:06 +00001135"allocate_lock() -> lock object\n\
1136(allocate() is an obsolete synonym)\n\
1137\n\
Alexander Belopolsky977a6842010-08-16 20:17:07 +00001138Create a new lock object. See help(LockType) for information 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\
Guido van Rossum65d5b571998-12-21 19:32:43 +00001330call the PyThread_allocate_lock() function. 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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 PyObject *m, *d, *timeout_max;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 /* Initialize types: */
Antoine Pitrou5af4f4b2010-08-09 22:38:19 +00001359 if (PyType_Ready(&localdummytype) < 0)
1360 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 if (PyType_Ready(&localtype) < 0)
1362 return NULL;
1363 if (PyType_Ready(&Locktype) < 0)
1364 return NULL;
1365 if (PyType_Ready(&RLocktype) < 0)
1366 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* Create the module and add the functions */
1369 m = PyModule_Create(&threadmodule);
1370 if (m == NULL)
1371 return NULL;
Antoine Pitrou7c3e5772010-04-14 15:44:10 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 timeout_max = PyFloat_FromDouble(PY_TIMEOUT_MAX / 1000000);
1374 if (!timeout_max)
1375 return NULL;
1376 if (PyModule_AddObject(m, "TIMEOUT_MAX", timeout_max) < 0)
1377 return NULL;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* Add a symbolic constant */
1380 d = PyModule_GetDict(m);
Antoine Pitroufcf81fd2011-02-28 22:03:34 +00001381 ThreadError = PyExc_RuntimeError;
1382 Py_INCREF(ThreadError);
Victor Stinner754851f2011-04-19 23:58:51 +02001383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 PyDict_SetItemString(d, "error", ThreadError);
1385 Locktype.tp_doc = lock_doc;
1386 Py_INCREF(&Locktype);
1387 PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype);
Antoine Pitrou434736a2009-11-10 18:46:01 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 Py_INCREF(&RLocktype);
1390 if (PyModule_AddObject(m, "RLock", (PyObject *)&RLocktype) < 0)
1391 return NULL;
Jim Fultond15dc062004-07-14 19:11:50 +00001392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 Py_INCREF(&localtype);
1394 if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
1395 return NULL;
Antoine Pitrou65c9c642009-10-30 17:25:12 +00001396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 nb_threads = 0;
1398
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001399 str_dict = PyUnicode_InternFromString("__dict__");
1400 if (str_dict == NULL)
1401 return NULL;
1402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 /* Initialize the C thread library */
1404 PyThread_init_thread();
1405 return m;
Guido van Rossum1984f1e1992-08-04 12:41:02 +00001406}