Jupyter笔记本中的线程 [英] Threading in Jupyter notebook

查看:124
本文介绍了Jupyter笔记本中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Jupyter笔记本中运行以下代码段:

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()

这是输出:

    worker Starting
    Thread-10 Starting
    my_service Starting

我没有看到以下预期输出:

I do not see the following expected outputs:

    Thread-10 Exiting
    worker Exiting
    my_service Exiting

(我在使用命令行运行python文件时确实得到了这些信息)

(I do get these while running my python file using the command Line)

这在Jupyter笔记本电脑中很常见吗?

Is this typical in a Jupyter notebook?

推荐答案

一旦该单元的主线程中的Python语句结束,Jupyter就会收集输出并将其显示为该单元的结果.

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.

在启动工作线程之后,尝试在Jupyter上单元的末尾添加time.sleep(1),它应该可以工作.

Try adding a time.sleep(1) at the end of your cell on Jupyter, after starting the worker-threads, and it should work.

这篇关于Jupyter笔记本中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆