问题
I tried running the following code snippet in a Jupyter notebook:
import threading
import time
def worker():
print(threading.current_thread().getName(), 'Starting')
time.sleep(0.2)
print(threading.current_thread().getName(), 'Exiting')
def my_service():
print(threading.current_thread().getName(), 'Starting')
time.sleep(0.3)
print(threading.current_thread().getName(), 'Exiting')
t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name
w.start()
w2.start()
t.start()
This is the output:
worker Starting
Thread-10 Starting
my_service Starting
I do not see the following expected outputs:
Thread-10 Exiting
worker Exiting
my_service Exiting
(I do get these while running my python file using the command Line)
Is this typical in a Jupyter notebook?
回答1:
As soon as the Python statements in the main-thread for the cell are over, Jupyter will collect the output and present that as the cell-result.
Try adding a time.sleep(1)
at the end of your cell on Jupyter, after starting the worker-threads, and it should work.
来源:https://stackoverflow.com/questions/59633435/threading-in-jupyter-notebook