Python中的守护线程是什么?如何理解和使用?

2021年11月16日19:22:16 发表评论 785 次浏览

通过小例子和实际示例了解什么是守护线程,以及如何在 Python 中设置守护线程。

在本教程中,你将理解什么是 Python 中的守护线程以及如何设置它们,你应该对本教程中的线程有基本的了解。

Python中的守护线程是什么?守护线程是在主线程死亡时死亡的线程,也称为非阻塞线程。通常,主线程应该等待其他线程完成才能退出程序,但是如果你设置了守护进程标志,你可以让线程做它的工作而忘记它,当程序退出时,它会被杀死自动地。

这在许多情况下都很有用,假设你正在执行一些网络抓取任务,并且你想要创建一个线程,每当你正在抓取的特定网站中插入新项目时,它都会在电子邮件中提醒你。

另一个示例,你可能希望创建一个线程来监视程序中的日志文件,并在发生严重错误时提醒你。

Python如何理解守护线程?在本教程的最后,我们将与你分享一些我们发现对使用守护线程很有用的教程。

既然知道了守护线程是什么,也知道它的用处,那我们举个Python守护线程示例,下面的代码启动一个非守护线程并启动它,然后我们也结束了主线程:

import threading
import time

def func():
    while True:
        print(f"[{threading.current_thread().name}] Printing this message every 2 seconds")
        time.sleep(2)

# initiate the thread to call the above function
normal_thread = threading.Thread(target=func, name="normal_thread")
# start the thread
normal_thread.start()
# sleep for 4 seconds and end the main thread
time.sleep(4)
# the main thread ends

func()函数应该永远运行,因为我们设置Truewhile循环的条件。启动该线程后,我们在主线程中进行简单的睡眠并退出程序。

Python中的守护线程是什么?但是,如果你运行它,你会看到该程序一直在运行并且不允许你退出(仅当你关闭窗口时):

[normal_thread] Printing this message every 2 seconds
[normal_thread] Printing this message every 2 seconds
[normal_thread] Printing this message every 2 seconds
[normal_thread] Printing this message every 2 seconds
[normal_thread] Printing this message every 2 seconds
...goes forever

因此,非守护线程使程序在完成之前拒绝退出。

Python如何理解守护线程?下面的例子这次启动了一个守护线程:

import threading
import time

def func_1():
    while True:
        print(f"[{threading.current_thread().name}] Printing this message every 2 seconds")
        time.sleep(2)

# initiate the thread with daemon set to True
daemon_thread = threading.Thread(target=func_1, name="daemon-thread", daemon=True)
# or
# daemon_thread.daemon = True
# or
# daemon_thread.setDaemon(True)
daemon_thread.start()
# sleep for 10 seconds and end the main thread
time.sleep(4)
# the main thread ends

在以上的Python守护线程示例中,现在我们传递daemon=Truethreading.Threadclass 以表明它是一个守护线程,你还可以访问该daemon属性True或使用该setDaemon(True)方法。

让我们执行程序:

[daemon-thread] Printing this message every 2 seconds
[daemon-thread] Printing this message every 2 seconds

这次一旦主线程完成其工作,守护线程也会自动被杀死并退出程序。

真实例子

以下是我们使用守护线程完成任务的一些教程:

  • 在 Python 中制作键盘记录器:一个守护线程,用于将键盘记录发送到我们的电子邮件或保存到文件。
  • 在 Python 中制作端口扫描器:多个守护线程来扫描端口。
  • 使用 Python 暴力破解 FTP 服务器:多个守护线程尝试 FTP 登录。
  • 用 Python 制作一个聊天应用程序:一个守护线程,它监听来自网络的即将到来的消息,并将它们打印到控制台。
木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: