3 /* Interface to Sjoerd's portable C thread library */
8 #error "Error! The rest of Python is not compiled with thread support."
9 #error "Rerun configure, adding a --with-threads option."
10 #error "Then run `make clean' followed by `make'."
15 static PyObject
*ThreadError
;
22 PyThread_type_lock lock_lock
;
26 lock_dealloc(lockobject
*self
)
28 assert(self
->lock_lock
);
29 /* Unlock the lock so it's safe to free it */
30 PyThread_acquire_lock(self
->lock_lock
, 0);
31 PyThread_release_lock(self
->lock_lock
);
33 PyThread_free_lock(self
->lock_lock
);
38 lock_PyThread_acquire_lock(lockobject
*self
, PyObject
*args
)
42 if (!PyArg_ParseTuple(args
, "|i:acquire", &i
))
45 Py_BEGIN_ALLOW_THREADS
46 i
= PyThread_acquire_lock(self
->lock_lock
, i
);
49 return PyBool_FromLong((long)i
);
52 PyDoc_STRVAR(acquire_doc
,
53 "acquire([wait]) -> None or bool\n\
54 (acquire_lock() is an obsolete synonym)\n\
56 Lock the lock. Without argument, this blocks if the lock is already\n\
57 locked (even by the same thread), waiting for another thread to release\n\
58 the lock, and return None once the lock is acquired.\n\
59 With an argument, this will only block if the argument is true,\n\
60 and the return value reflects whether the lock is acquired.\n\
61 The blocking operation is not interruptible.");
64 lock_PyThread_release_lock(lockobject
*self
)
66 /* Sanity check: the lock must be locked */
67 if (PyThread_acquire_lock(self
->lock_lock
, 0)) {
68 PyThread_release_lock(self
->lock_lock
);
69 PyErr_SetString(ThreadError
, "release unlocked lock");
73 PyThread_release_lock(self
->lock_lock
);
78 PyDoc_STRVAR(release_doc
,
80 (release_lock() is an obsolete synonym)\n\
82 Release the lock, allowing another thread that is blocked waiting for\n\
83 the lock to acquire the lock. The lock must be in the locked state,\n\
84 but it needn't be locked by the same thread that unlocks it.");
87 lock_locked_lock(lockobject
*self
)
89 if (PyThread_acquire_lock(self
->lock_lock
, 0)) {
90 PyThread_release_lock(self
->lock_lock
);
91 return PyBool_FromLong(0L);
93 return PyBool_FromLong(1L);
96 PyDoc_STRVAR(locked_doc
,
98 (locked_lock() is an obsolete synonym)\n\
100 Return whether the lock is in the locked state.");
102 static PyMethodDef lock_methods
[] = {
103 {"acquire_lock", (PyCFunction
)lock_PyThread_acquire_lock
,
104 METH_VARARGS
, acquire_doc
},
105 {"acquire", (PyCFunction
)lock_PyThread_acquire_lock
,
106 METH_VARARGS
, acquire_doc
},
107 {"release_lock", (PyCFunction
)lock_PyThread_release_lock
,
108 METH_NOARGS
, release_doc
},
109 {"release", (PyCFunction
)lock_PyThread_release_lock
,
110 METH_NOARGS
, release_doc
},
111 {"locked_lock", (PyCFunction
)lock_locked_lock
,
112 METH_NOARGS
, locked_doc
},
113 {"locked", (PyCFunction
)lock_locked_lock
,
114 METH_NOARGS
, locked_doc
},
115 {"__enter__", (PyCFunction
)lock_PyThread_acquire_lock
,
116 METH_VARARGS
, acquire_doc
},
117 {"__exit__", (PyCFunction
)lock_PyThread_release_lock
,
118 METH_VARARGS
, release_doc
},
119 {NULL
} /* sentinel */
122 static PyTypeObject Locktype
= {
123 PyVarObject_HEAD_INIT(&PyType_Type
, 0)
124 "thread.lock", /*tp_name*/
125 sizeof(lockobject
), /*tp_size*/
128 (destructor
)lock_dealloc
, /*tp_dealloc*/
134 0, /* tp_as_number */
135 0, /* tp_as_sequence */
136 0, /* tp_as_mapping */
142 0, /* tp_as_buffer */
147 0, /* tp_richcompare */
148 0, /* tp_weaklistoffset */
151 lock_methods
, /* tp_methods */
158 self
= PyObject_New(lockobject
, &Locktype
);
161 self
->lock_lock
= PyThread_allocate_lock();
162 if (self
->lock_lock
== NULL
) {
165 PyErr_SetString(ThreadError
, "can't allocate lock");
170 /* Thread-local objects */
172 #include "structmember.h"
183 local_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kw
)
188 if (type
->tp_init
== PyBaseObject_Type
.tp_init
189 && ((args
&& PyObject_IsTrue(args
))
190 || (kw
&& PyObject_IsTrue(kw
)))) {
191 PyErr_SetString(PyExc_TypeError
,
192 "Initialization arguments are not supported");
196 self
= (localobject
*)type
->tp_alloc(type
, 0);
204 self
->dict
= NULL
; /* making sure */
205 self
->key
= PyString_FromFormat("thread.local.%p", self
);
206 if (self
->key
== NULL
)
209 self
->dict
= PyDict_New();
210 if (self
->dict
== NULL
)
213 tdict
= PyThreadState_GetDict();
215 PyErr_SetString(PyExc_SystemError
,
216 "Couldn't get thread-state dictionary");
220 if (PyDict_SetItem(tdict
, self
->key
, self
->dict
) < 0)
223 return (PyObject
*)self
;
231 local_traverse(localobject
*self
, visitproc visit
, void *arg
)
233 Py_VISIT(self
->args
);
235 Py_VISIT(self
->dict
);
240 local_clear(localobject
*self
)
243 Py_CLEAR(self
->args
);
245 Py_CLEAR(self
->dict
);
250 local_dealloc(localobject
*self
)
252 PyThreadState
*tstate
;
254 && (tstate
= PyThreadState_Get())
256 for(tstate
= PyInterpreterState_ThreadHead(tstate
->interp
);
258 tstate
= PyThreadState_Next(tstate
))
260 PyDict_GetItem(tstate
->dict
, self
->key
))
261 PyDict_DelItem(tstate
->dict
, self
->key
);
265 Py_TYPE(self
)->tp_free((PyObject
*)self
);
269 _ldict(localobject
*self
)
271 PyObject
*tdict
, *ldict
;
273 tdict
= PyThreadState_GetDict();
275 PyErr_SetString(PyExc_SystemError
,
276 "Couldn't get thread-state dictionary");
280 ldict
= PyDict_GetItem(tdict
, self
->key
);
282 ldict
= PyDict_New(); /* we own ldict */
287 int i
= PyDict_SetItem(tdict
, self
->key
, ldict
);
288 Py_DECREF(ldict
); /* now ldict is borrowed */
293 Py_CLEAR(self
->dict
);
295 self
->dict
= ldict
; /* still borrowed */
297 if (Py_TYPE(self
)->tp_init
!= PyBaseObject_Type
.tp_init
&&
298 Py_TYPE(self
)->tp_init((PyObject
*)self
,
299 self
->args
, self
->kw
) < 0) {
300 /* we need to get rid of ldict from thread so
301 we create a new one the next time we do an attr
303 PyDict_DelItem(tdict
, self
->key
);
309 /* The call to tp_init above may have caused another thread to run.
310 Install our ldict again. */
311 if (self
->dict
!= ldict
) {
312 Py_CLEAR(self
->dict
);
321 local_setattro(localobject
*self
, PyObject
*name
, PyObject
*v
)
325 ldict
= _ldict(self
);
329 return PyObject_GenericSetAttr((PyObject
*)self
, name
, v
);
333 local_getdict(localobject
*self
, void *closure
)
335 if (self
->dict
== NULL
) {
336 PyErr_SetString(PyExc_AttributeError
, "__dict__");
340 Py_INCREF(self
->dict
);
344 static PyGetSetDef local_getset
[] = {
345 {"__dict__", (getter
)local_getdict
, (setter
)NULL
,
346 "Local-data dictionary", NULL
},
347 {NULL
} /* Sentinel */
350 static PyObject
*local_getattro(localobject
*, PyObject
*);
352 static PyTypeObject localtype
= {
353 PyVarObject_HEAD_INIT(NULL
, 0)
354 /* tp_name */ "thread._local",
355 /* tp_basicsize */ sizeof(localobject
),
357 /* tp_dealloc */ (destructor
)local_dealloc
,
363 /* tp_as_number */ 0,
364 /* tp_as_sequence */ 0,
365 /* tp_as_mapping */ 0,
369 /* tp_getattro */ (getattrofunc
)local_getattro
,
370 /* tp_setattro */ (setattrofunc
)local_setattro
,
371 /* tp_as_buffer */ 0,
372 /* tp_flags */ Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
,
373 /* tp_doc */ "Thread-local data",
374 /* tp_traverse */ (traverseproc
)local_traverse
,
375 /* tp_clear */ (inquiry
)local_clear
,
376 /* tp_richcompare */ 0,
377 /* tp_weaklistoffset */ 0,
382 /* tp_getset */ local_getset
,
384 /* tp_dict */ 0, /* internal use */
385 /* tp_descr_get */ 0,
386 /* tp_descr_set */ 0,
387 /* tp_dictoffset */ offsetof(localobject
, dict
),
390 /* tp_new */ local_new
,
391 /* tp_free */ 0, /* Low-level free-mem routine */
392 /* tp_is_gc */ 0, /* For PyObject_IS_GC */
396 local_getattro(localobject
*self
, PyObject
*name
)
398 PyObject
*ldict
, *value
;
400 ldict
= _ldict(self
);
404 if (Py_TYPE(self
) != &localtype
)
405 /* use generic lookup for subtypes */
406 return PyObject_GenericGetAttr((PyObject
*)self
, name
);
408 /* Optimization: just look in dict ourselves */
409 value
= PyDict_GetItem(ldict
, name
);
411 /* Fall back on generic to get __class__ and __dict__ */
412 return PyObject_GenericGetAttr((PyObject
*)self
, name
);
418 /* Module functions */
421 PyInterpreterState
*interp
;
428 t_bootstrap(void *boot_raw
)
430 struct bootstate
*boot
= (struct bootstate
*) boot_raw
;
431 PyThreadState
*tstate
;
434 tstate
= PyThreadState_New(boot
->interp
);
436 PyEval_AcquireThread(tstate
);
437 res
= PyEval_CallObjectWithKeywords(
438 boot
->func
, boot
->args
, boot
->keyw
);
440 if (PyErr_ExceptionMatches(PyExc_SystemExit
))
445 "Unhandled exception in thread started by ");
446 file
= PySys_GetObject("stderr");
448 PyFile_WriteObject(boot
->func
, file
, 0);
450 PyObject_Print(boot
->func
, stderr
, 0);
451 PySys_WriteStderr("\n");
457 Py_DECREF(boot
->func
);
458 Py_DECREF(boot
->args
);
459 Py_XDECREF(boot
->keyw
);
461 PyThreadState_Clear(tstate
);
462 PyThreadState_DeleteCurrent();
463 PyThread_exit_thread();
467 thread_PyThread_start_new_thread(PyObject
*self
, PyObject
*fargs
)
469 PyObject
*func
, *args
, *keyw
= NULL
;
470 struct bootstate
*boot
;
473 if (!PyArg_UnpackTuple(fargs
, "start_new_thread", 2, 3,
474 &func
, &args
, &keyw
))
476 if (!PyCallable_Check(func
)) {
477 PyErr_SetString(PyExc_TypeError
,
478 "first arg must be callable");
481 if (!PyTuple_Check(args
)) {
482 PyErr_SetString(PyExc_TypeError
,
483 "2nd arg must be a tuple");
486 if (keyw
!= NULL
&& !PyDict_Check(keyw
)) {
487 PyErr_SetString(PyExc_TypeError
,
488 "optional 3rd arg must be a dictionary");
491 boot
= PyMem_NEW(struct bootstate
, 1);
493 return PyErr_NoMemory();
494 boot
->interp
= PyThreadState_GET()->interp
;
501 PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
502 ident
= PyThread_start_new_thread(t_bootstrap
, (void*) boot
);
504 PyErr_SetString(ThreadError
, "can't start new thread");
511 return PyInt_FromLong(ident
);
514 PyDoc_STRVAR(start_new_doc
,
515 "start_new_thread(function, args[, kwargs])\n\
516 (start_new() is an obsolete synonym)\n\
518 Start a new thread and return its identifier. The thread will call the\n\
519 function with positional arguments from the tuple args and keyword arguments\n\
520 taken from the optional dictionary kwargs. The thread exits when the\n\
521 function returns; the return value is ignored. The thread will also exit\n\
522 when the function raises an unhandled exception; a stack trace will be\n\
523 printed unless the exception is SystemExit.\n");
526 thread_PyThread_exit_thread(PyObject
*self
)
528 PyErr_SetNone(PyExc_SystemExit
);
532 PyDoc_STRVAR(exit_doc
,
534 (PyThread_exit_thread() is an obsolete synonym)\n\
536 This is synonymous to ``raise SystemExit''. It will cause the current\n\
537 thread to exit silently unless the exception is caught.");
540 thread_PyThread_interrupt_main(PyObject
* self
)
542 PyErr_SetInterrupt();
547 PyDoc_STRVAR(interrupt_doc
,
550 Raise a KeyboardInterrupt in the main thread.\n\
551 A subthread can use this function to interrupt the main thread."
556 thread_PyThread_exit_prog(PyObject
*self
, PyObject
*args
)
559 if (!PyArg_ParseTuple(args
, "i:exit_prog", &sts
))
561 Py_Exit(sts
); /* Calls PyThread_exit_prog(sts) or _PyThread_exit_prog(sts) */
562 for (;;) { } /* Should not be reached */
566 static lockobject
*newlockobject(void);
569 thread_PyThread_allocate_lock(PyObject
*self
)
571 return (PyObject
*) newlockobject();
574 PyDoc_STRVAR(allocate_doc
,
575 "allocate_lock() -> lock object\n\
576 (allocate() is an obsolete synonym)\n\
578 Create a new lock object. See LockType.__doc__ for information about locks.");
581 thread_get_ident(PyObject
*self
)
584 ident
= PyThread_get_thread_ident();
586 PyErr_SetString(ThreadError
, "no current thread ident");
589 return PyInt_FromLong(ident
);
592 PyDoc_STRVAR(get_ident_doc
,
593 "get_ident() -> integer\n\
595 Return a non-zero integer that uniquely identifies the current thread\n\
596 amongst other threads that exist simultaneously.\n\
597 This may be used to identify per-thread resources.\n\
598 Even though on some platforms threads identities may appear to be\n\
599 allocated consecutive numbers starting at 1, this behavior should not\n\
600 be relied upon, and the number should be seen purely as a magic cookie.\n\
601 A thread's identity may be reused for another thread after it exits.");
604 thread_stack_size(PyObject
*self
, PyObject
*args
)
607 Py_ssize_t new_size
= 0;
610 if (!PyArg_ParseTuple(args
, "|n:stack_size", &new_size
))
614 PyErr_SetString(PyExc_ValueError
,
615 "size must be 0 or a positive value");
619 old_size
= PyThread_get_stacksize();
621 rc
= PyThread_set_stacksize((size_t) new_size
);
623 PyErr_Format(PyExc_ValueError
,
624 "size not valid: %zd bytes",
629 PyErr_SetString(ThreadError
,
630 "setting stack size not supported");
634 return PyInt_FromSsize_t((Py_ssize_t
) old_size
);
637 PyDoc_STRVAR(stack_size_doc
,
638 "stack_size([size]) -> size\n\
640 Return the thread stack size used when creating new threads. The\n\
641 optional size argument specifies the stack size (in bytes) to be used\n\
642 for subsequently created threads, and must be 0 (use platform or\n\
643 configured default) or a positive integer value of at least 32,768 (32k).\n\
644 If changing the thread stack size is unsupported, a ThreadError\n\
645 exception is raised. If the specified size is invalid, a ValueError\n\
646 exception is raised, and the stack size is unmodified. 32k bytes\n\
647 currently the minimum supported stack size value to guarantee\n\
648 sufficient stack space for the interpreter itself.\n\
650 Note that some platforms may have particular restrictions on values for\n\
651 the stack size, such as requiring a minimum stack size larger than 32kB or\n\
652 requiring allocation in multiples of the system memory page size\n\
653 - platform documentation should be referred to for more information\n\
654 (4kB pages are common; using multiples of 4096 for the stack size is\n\
655 the suggested approach in the absence of more specific information).");
657 static PyMethodDef thread_methods
[] = {
658 {"start_new_thread", (PyCFunction
)thread_PyThread_start_new_thread
,
661 {"start_new", (PyCFunction
)thread_PyThread_start_new_thread
,
664 {"allocate_lock", (PyCFunction
)thread_PyThread_allocate_lock
,
665 METH_NOARGS
, allocate_doc
},
666 {"allocate", (PyCFunction
)thread_PyThread_allocate_lock
,
667 METH_NOARGS
, allocate_doc
},
668 {"exit_thread", (PyCFunction
)thread_PyThread_exit_thread
,
669 METH_NOARGS
, exit_doc
},
670 {"exit", (PyCFunction
)thread_PyThread_exit_thread
,
671 METH_NOARGS
, exit_doc
},
672 {"interrupt_main", (PyCFunction
)thread_PyThread_interrupt_main
,
673 METH_NOARGS
, interrupt_doc
},
674 {"get_ident", (PyCFunction
)thread_get_ident
,
675 METH_NOARGS
, get_ident_doc
},
676 {"stack_size", (PyCFunction
)thread_stack_size
,
680 {"exit_prog", (PyCFunction
)thread_PyThread_exit_prog
,
683 {NULL
, NULL
} /* sentinel */
687 /* Initialization function */
689 PyDoc_STRVAR(thread_doc
,
690 "This module provides primitive operations to write multi-threaded programs.\n\
691 The 'threading' module provides a more convenient interface.");
693 PyDoc_STRVAR(lock_doc
,
694 "A lock object is a synchronization primitive. To create a lock,\n\
695 call the PyThread_allocate_lock() function. Methods are:\n\
697 acquire() -- lock the lock, possibly blocking until it can be obtained\n\
698 release() -- unlock of the lock\n\
699 locked() -- test whether the lock is currently locked\n\
701 A lock is not owned by the thread that locked it; another thread may\n\
702 unlock it. A thread attempting to lock a lock that it has already locked\n\
703 will block until another thread unlocks it. Deadlocks may ensue.");
710 /* Initialize types: */
711 if (PyType_Ready(&localtype
) < 0)
714 /* Create the module and add the functions */
715 m
= Py_InitModule3("thread", thread_methods
, thread_doc
);
719 /* Add a symbolic constant */
720 d
= PyModule_GetDict(m
);
721 ThreadError
= PyErr_NewException("thread.error", NULL
, NULL
);
722 PyDict_SetItemString(d
, "error", ThreadError
);
723 Locktype
.tp_doc
= lock_doc
;
724 if (PyType_Ready(&Locktype
) < 0)
726 Py_INCREF(&Locktype
);
727 PyDict_SetItemString(d
, "LockType", (PyObject
*)&Locktype
);
729 Py_INCREF(&localtype
);
730 if (PyModule_AddObject(m
, "_local", (PyObject
*)&localtype
) < 0)
733 /* Initialize the C thread library */
734 PyThread_init_thread();