Spawning a new thread while importing

2019-05-26 02:46发布

问题:

Python's threading documentation states:

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.

I'm looking for example code that demonstrates this restriction.

回答1:

I tried this, a module that spawns a thread whose target tries to import sys:

from threading import Thread

def my_target():
    import sys

thread = Thread(target=my_target)
thread.start()
thread.join()

When the python interpreter is launched and an attempt to import the module above is made, it indeed freezes.