Thread.start() never returns! Could this have something to do with the C implementation of the math library?
As @eryksun pointed out in the comment: math.factorial() is implemented as a C function that doesn't release GIL so no other Python code may run until it returns.
Note: multiprocessing
version should work as is: each Python process has its own GIL.
factorial(1000000000)
has hundreds millions of digits. Try import time; time.sleep(10)
as dummy calculation instead.
If you have issues with multithreaded code in IDLE then try the same code from the command line, to make sure that the error persists.
If p.is_alive()
returns False
after p.start()
is already called then it might mean that there is an error in f()
function e.g., MemoryError
.
On my machine, p.is_alive()
returns True
and one of cpus is at 100% if I paste your code from the question into Python shell.
Unrelated: remove wildcard imports such as from multiprocessing import *
. They may shadow other names in your code so that you can't be sure what a given name means e.g., threading
could define eval
function (it doesn't but it could) with a similar but different semantics that might break your code silently.
I want my program to be able to handle ridiculous inputs from the user gracefully
If you pass user input directly to eval()
then the user can do anything.
Is there any way to get a process to print, say, an error message without constructing a pipe or other similar structure?
It is an ordinary Python code:
print(message) # works
The difference is that if several processes run print()
then the output might be garbled. You could use a lock to synchronize print()
calls.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…