This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author valhallasw
Recipients docs@python, valhallasw
Date 2012-06-17.14:23:53
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1339943036.28.0.366324520843.issue15097@psf.upfronthosting.co.za>
In-reply-to
Content
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).
History
Date User Action Args
2012-06-17 14:23:56valhallaswsetrecipients: + valhallasw, docs@python
2012-06-17 14:23:56valhallaswsetmessageid: <1339943036.28.0.366324520843.issue15097@psf.upfronthosting.co.za>
2012-06-17 14:23:55valhallaswlinkissue15097 messages
2012-06-17 14:23:54valhallaswcreate