New submission from Merlijn van Deen <[email protected]>:
http://docs.python.org/library/threading.html#importing-in-threaded-code
Currently, the documentation states
"Firstly, other than in the main module, an import should not have the side
effect of spawning a new thread and then waiting for that thread in any way.
Failing to abide by this restriction can lead to a deadlock if the spawned
thread directly or indirectly attempts to import a module."
which, I think, fails to make the main point: a call to import acquires the
import lock. A call to import from a second thread will thus block.
As such, I would suggest rephrasing it to something like:
"Firstly, an import acquires the import lock for that thread. Therefore, the
import should not have the side effect of waiting for a different thread in any
way, as this can lead to a deadlock if that thread directly or indirectly
attempts to import a module."
There are two additional points that might be interesting to note:
(1) Any module can be imported. If the import causes a deadlock, that is a bad
thing. Every module *will* be imported by tools such as nosetests.
(1b) so: never, ever, have code that causes locks in a different thread in
module level code witout 'if __name__=="__main__" ' blocks?
(2) The lock is also acquired if a module has already been imported. For
instance, in
import sys # (1)
def f():
import sys # (2)
the import lock is acquired in (1) /and/ (2).
Adding example code and/or a flow diagram might be a bit too much, but it does
clarify how easy it is to make this mistake. See the attached for an example
(both a simple example script, as well as a flow diagram explaining what
happens).
----------
assignee: docs@python
components: Documentation
files: deadlock.py
messages: 163068
nosy: docs@python, valhallasw
priority: normal
severity: normal
status: open
title: Improving wording on the thread-safeness of import
type: enhancement
Added file: http://bugs.python.org/file26037/deadlock.py
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue15097>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com