Threading in Jupyter notebook

和自甴很熟 提交于 2021-02-10 18:30:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!