-
-
Notifications
You must be signed in to change notification settings - Fork 30.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
KeyError at exit after 'import threading' in other thread #44231
Comments
Python 2.4.3 on Windows 2000, though the code in I'm using Python embedded in a multithreaded C++ Error in atexit._run_exitfuncs:
Traceback (most recent call last):
File "C:\Python24\lib\atexit.py", line 24, in
_run_exitfuncs
func(*targs, **kargs)
File "C:\Python24\lib\threading.py", line 636, in
__exitfunc
self._Thread__delete()
File "C:\Python24\lib\threading.py", line 522, in
__delete
del _active[_get_ident()]
KeyError: 680
Error in sys.exitfunc:
Traceback (most recent call last):
File "C:\Python24\lib\atexit.py", line 24, in
_run_exitfuncs
func(*targs, **kargs)
File "C:\Python24\lib\threading.py", line 636, in
__exitfunc
self._Thread__delete()
File "C:\Python24\lib\threading.py", line 522, in
__delete
del _active[_get_ident()]
KeyError: 680 The reason seems to be that the threading module uses I didn't study this in all detail, but it seems to me |
Well, I don't think you should be calling Py_Finalize() from the non-main thread. That just seems unsafe to me. Regardless, though, could you write up some quick Python code that triggers this? |
I'm not calling Py_Finalize from a non-main thread. What I called "thread B" is the main thread. It's the script that first imports the threading module that runs in a non-main thread (and running user-defined scripts in non-main threads is hopefully not unsafe, or there wouldn't be much point in supporting multithreading at all in Python). It didn't even occur to me that this could be reproduced in pure Python code, so I didn't include an example in my original post. Of course, it can - see attachment. Tested on Python 2.3.5 on Mac OS X. |
Thanks for the test code. I have no clue when I or anyone else will get to this, but the report and testing code is appreciated. |
threadingbug.py doesn't fail for me on trunk (linux), anyone else? the output I get is always: Main thread ID: -134346528 |
I'm not sure what you mean by "doesn't fail" - from the output you quote, Would you classify that KeyError as expected behavior? |
gah, sorry i misread the report. you are correct. |
Is the bug avoided if you import threading first and use it instead of |
If a python daemon thread is still running when the interpreter exits, Here is another example, which does not use imports. In the majority of runs, I get an error message: And more interestingly, about every 50 runs, the process segfaults... |
Yes. The bug happens when the (first) import of threading and the call to Py_Finalize() Has anyone checked if the solution I propose in the first post makes sense? |
FWIW, Amaury's example runs without error on trunk and py3k (OS X 10.5). 2.6 prints the following: 3.1 seg faults |
I have the impression we're tracking two completely unrelated problems in this tracker item. As to "needs patch" regarding my problem: Here's the solution I proposed in my original post in patch form - I'm just not sure if it is correct. I don't recommend applying this until someone who is familiar with the workings of the threading module has confirmed that removing self from _active is the right thing to do (and that what I'm doing is the accepted pythonic way of removing a dictionary entry by value). Index: Lib/threading.py --- Lib/threading.py (revision 77598)
+++ Lib/threading.py (working copy)
@@ -611,7 +611,11 @@
try:
with _active_limbo_lock:
- del _active[_get_ident()]
+ for k, v in _active.iteritems():
+ if v is self: break
+ else:
+ assert False, "thread instance not found in _active"
+ del _active[k]
# There must not be any python code between the previous line
# and after the lock is released. Otherwise a tracing function
# could try to acquire the lock again in the same thread, (in |
I think the fix to Christian's issue is just: Index: Lib/threading.py --- Lib/threading.py (révision 79470)
+++ Lib/threading.py (copie de travail)
@@ -579,7 +579,7 @@
try:
# We don't call self.__delete() because it also
# grabs _active_limbo_lock.
- del _active[_get_ident()]
+ del _active[self.__ident]
except:
pass
@@ -615,7 +615,7 @@
try:
with _active_limbo_lock:
- del _active[_get_ident()]
+ del _active[self.__ident]
# There must not be any python code between the previous line
# and after the lock is released. Otherwise a tracing function
# could try to acquire the lock again in the same thread, (in Now we just need to add a test for it in test_threading. |
From my limited experience using cx_Freeze 4.1.2 with Python 2.6.5, it seems that this issue is triggered in a cx_Frozen program simply by having |
Sorry I should have said, I'm running on Windows 2000 SP4. |
A follow-on re the cx_Freeze issue: I looked at the source code, and found it doesn't seem to be doing any thread creation. But I found that in the initscripts/Console.py, there are the following lines: if sys.version_info[:2] >= (2, 5):
module = sys.modules.get("threading")
if module is not None:
module._shutdown() If these lines are commented-out, then the error message at exit does not occur. |
Another solution for cx-freeze problem: Which can be added in ConsoleKeepPath.c for instance |
I encountered this issue recently in Python 3.2 and wanted to make some observations about it. The real problem here is not the KeyError. Though the suggested patches would fix the KeyError symptom, they do not fix the underlying issue. The underlying issue is the threading module assumes that it is imported from the Python main thread. When alien threads exist, the threading module may be imported (directly or indirectly) from a thread that is not the Python main thread, causing the wrong thread to be marked as the Python main thread. The resulting problems of the wrong thread being marked as the Python main thread appear to be minor. The KeyError at exit is one of them. Another problem I encountered was with confusion in a threaded debugger that displayed my alien thread as the Python main thread, and the Python main thread as the alien thread. In my project I can easily work around this by importing the threading module in a root package that is extremely likely to be imported from the Python main thread, causing the correct thread to be marked as the main thread. Since I have a workaround for my project, in addition to the relatively minor issues that result from this behavior, I haven't spent any time looking into how to fix the underlying issue. If I have the time, I'll suggest one. |
Only few people seem to use daemon threads. We do and see this problem often with Python 2.7. How difficult is it to get this fixed for 2.7? Is there a way to work around this problem? |
related: issue bpo-39042 "Use the runtime's main thread ID in the threading module." |
The output is different now. I update the script for python 3: --------------------------------------------- import _thread as thread
import time
def start():
print("Secondary thread ID:", thread.get_ident())
import threading
print("Main thread ID:", thread.get_ident())
thread.start_new_thread(start, ())
time.sleep(1) and the output is: --------------------------------------------- Main thread ID: 4432801280
Secondary thread ID: 123145384259584
Exception ignored in: <module 'threading' from '/Users/iritkatriel/src/cpython-perf/Lib/threading.py'>
Traceback (most recent call last):
File "/Users/iritkatriel/src/cpython-perf/Lib/threading.py", line 1512, in _shutdown
assert tlock.locked()
^^^^^^^^^^^^^^^^^^^^^
AssertionError: |
I proposed PR 28549 to fix this very old threading issue. A C extension can spawn threads without using the threading module and then then run Python code which imports the threading module. In this case, threading._main_thread is the thread which imported first the threading module. My PR changes so threading._shutdown() simply ignores _main_thread when it happens. |
New changeset 95d3137 by Victor Stinner in branch 'main': |
New changeset 38c6773 by Miss Islington (bot) in branch '3.10': |
New changeset 94d19f6 by Victor Stinner in branch '3.9': |
Better late than never. I only took 15 years to fix this old bug :-D |
the bug occur on python 3.7? |
3.7 is no longer getting bug fixes. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: