import sys, time, threading, traceback try: import queue except ImportError: import Queue as queue Q = queue.Queue() class MyObject(object): def __init__(self): self.lock = threading.Semaphore(0) class MyThread(threading.Thread): def run(self): obj = Q.get() import sys obj.lock.release() thread = MyThread() thread.start() obj = MyObject() Q.put(obj) obj.lock.acquire() # alternatively, to show the location of the deadlock: while not obj.lock.acquire(False): for threadid, frame in sys._current_frames().items(): print("\n>>>", threadid, "<<<") traceback.print_stack(frame) time.sleep(1) """ Expected behaviour: ---------------------------------------------------------- Q = queue.Queue() [A] [B] obj=MyObject() obj=Q.get() [blocks] | : Q.put(obj) ----------------------> : | | obj.lock.acquire() [blocks] import sys : | : <------------------------ obj.lock.release() | | V V ---------------------------------------------------------- This is the behaviour when running using python script.py However, python -c 'import scripts' creates a deadlock; (*) marks what happens in cpython internally ---------------------------------------------------------- Q = queue.Queue() import_lock = Lock() (*) [A] [B] import_lock.acquire() (*) obj=Q.get() [blocks] | : obj=MyObject(); : | : Q.put(obj); ----------------------> : | | obj.lock.acquire() [blocks] import sys [causing, internally: : import_lock.acquire() [blocks] (*) : : === (deadlock) === ---------------------------------------------------------- """