[issue37416] If threading is not imported from the main thread it sees the wrong thread as the main thread.

Pavel Minaev report at bugs.python.org
Thu Jun 27 06:24:24 EDT 2019


Pavel Minaev <me at int19h.org> added the comment:

It's also possible to hit if using some native code that starts a background thread without going via threading, and runs Python code on that background thread. In that case, if that Python code then does "import threading", and threading hasn't been imported yet, then you have this same problem.

Here's a pure Python repro using ctypes on Win32:

#--------------------------
import sys, time
from ctypes import *

ThreadProc = WINFUNCTYPE(c_uint32, c_void_p)

@ThreadProc
def thread_proc(_):
    import threading
    print(threading.current_thread() is threading.main_thread())
    return 0

assert "threading" not in sys.modules
#import threading  # uncomment to fix

windll.kernel32.CreateThread(None, c_size_t(0), thread_proc, None, c_uint32(0), None)
time.sleep(1)

assert "threading" in sys.modules
import threading
print(threading.current_thread() is threading.main_thread())
#--------------------------

Here's the output:

>py -3 main.py
True
False
Exception ignored in: <module 'threading' from 'C:\\Python\\3.7-64\\lib\\threading.py'>
Traceback (most recent call last):
  File "C:\Python\3.7-64\lib\threading.py", line 1276, in _shutdown
    assert tlock.locked()
AssertionError:

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37416>
_______________________________________


More information about the Python-bugs-list mailing list