什么是python线程 [英] What is a python thread

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

问题描述

关于Python线程,我有几个问题.

I have several questions regarding Python threads.

  1. Python线程是Python还是OS实现?
  2. 当我使用htop时,多线程脚本具有多个条目-相同的内存消耗,相同的命令但不同的PID.这是否意味着[Python]线程实际上是一种特殊的过程? (我知道htop中有一个设置可以将这些线程显示为一个进程-Hide userland threads)
  3. 文档说:
  1. Is a Python thread a Python or OS implementation?
  2. When I use htop a multi-threaded script has multiple entries - the same memory consumption, the same command but a different PID. Does this mean that a [Python] thread is actually a special kind of process? (I know there is a setting in htop to show these threads as one process - Hide userland threads)
  3. Documentation says:

可以将一个线程标记为守护程序线程".的意义 标志是只有守护程序线程时,整个Python程序都会退出 离开了.

A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left.

我的解释/理解是:当所有非守护程序线程都终止时,主线程也会终止.

My interpretation/understanding was: main thread terminates when all non-daemon threads are terminated.

因此,如果仅保留守护程序线程时,整个Python程序就会退出",那么python守护程序线程不属于Python程序?

So python daemon threads are not part of Python program if "the entire Python program exits when only daemon threads are left"?

推荐答案

  1. Python线程是在我所知道的所有实现中都使用OS线程实现的(C Python,PyPy和Jython).对于每个Python线程,都有一个底层的OS线程.

  1. Python threads are implemented using OS threads in all implementations I know (C Python, PyPy and Jython). For each Python thread, there is an underlying OS thread.

某些操作系统(Linux是其中之一)在所有正在运行的进程的列表中显示了同一可执行文件启动的所有不同线程.这是操作系统的实现细节,而不是Python的实现细节.在某些其他操作系统上,列出所有进程时可能看不到那些线程.

Some operating systems (Linux being one of them) show all different threads launched by the same executable in the list of all running processes. This is an implementation detail of the OS, not of Python. On some other operating systems, you may not see those threads when listing all the processes.

最后一个非守护线程完成时,该过程将终止.届时,所有守护程序线程将被终止.因此,这些线程是您的进程的一部分,但并不能阻止它终止(而常规线程可以阻止它终止).那是用纯Python实现的.进程在调用系统_exit函数时终止(它将杀死所有线程),并且在主线程终止(或调用sys.exit)时,Python解释器将检查是否有另一个非守护进程线程在运行.如果没有,则调用_exit,否则它将等待非守护线程完成.

The process will terminate when the last non-daemon thread finishes. At that point, all the daemon threads will be terminated. So, those threads are part of your process, but are not preventing it from terminating (while a regular thread will prevent it). That is implemented in pure Python. A process terminates when the system _exit function is called (it will kill all threads), and when the main thread terminates (or sys.exit is called), the Python interpreter checks if there is another non-daemon thread running. If there is none, then it calls _exit, otherwise it waits for the non-daemon threads to finish.


守护程序线程标志由threading模块在纯Python中实现.加载模块后,将创建一个Thread对象来表示主线程,并将其_exitfunc方法注册为atexit挂钩.


The daemon thread flag is implemented in pure Python by the threading module. When the module is loaded, a Thread object is created to represent the main thread, and it's _exitfunc method is registered as an atexit hook.

此功能的代码为:

class _MainThread(Thread):

    def _exitfunc(self):
        self._Thread__stop()
        t = _pickSomeNonDaemonThread()
        if t:
            if __debug__:
                self._note("%s: waiting for other threads", self)
        while t:
            t.join()
            t = _pickSomeNonDaemonThread()
        if __debug__:
            self._note("%s: exiting", self)
        self._Thread__delete()

当调用sys.exit或主线程终止时,Python解释器将调用此函数.函数返回时,解释器将调用系统_exit函数.当只有守护程序线程在运行时(如果有),该函数将终止.

This function will be called by the Python interpreter when sys.exit is called, or when the main thread terminates. When the function returns, the interpreter will call the system _exit function. And the function will terminate, when there are only daemon threads running (if any).

调用_exit函数时,操作系统将终止所有进程线程,然后终止进程.直到所有非守护进程线程都完成后,Python运行时才会调用_exit函数.

When the _exit function is called, the OS will terminate all of the process threads, and then terminate the process. The Python runtime will not call the _exit function until all the non-daemon thread are done.

所有线程都是该过程的一部分.

All threads are part of the process.

我的解释/理解是:主线程在所有线程终止时终止 非守护线程终止.

My interpretation/understanding was: main thread terminates when all non-daemon threads are terminated.

因此,如果整个 仅保留守护程序线程时,Python程序会退出"?

So python daemon threads are not part of python program if "the entire Python program exits when only daemon threads are left"?

您的理解不正确.对于OS,一个进程由许多线程组成,所有线程都是相同的(对于OS的主线程,没有什么特别的,除了C运行时在main的末尾添加对_exit的调用)功能).而且操作系统不知道守护程序线程.这纯粹是一个Python概念.

Your understanding is incorrect. For the OS, a process is composed of many threads, all of which are equal (there is nothing special about the main thread for the OS, except that the C runtime add a call to _exit at the end of the main function). And the OS doesn't know about daemon threads. This is purely a Python concept.

Python解释器使用本机线程来实现Python线程,但必须记住创建的线程列表.并使用其atexit钩子确保_exit函数仅在最后一个非守护线程终止时才返回到操作系统.使用整个Python程序"时,文档指的是整个过程.

The Python interpreter uses native thread to implement Python thread, but has to remember the list of threads created. And using its atexit hook, it ensures that the _exit function returns to the OS only when the last non-daemon thread terminates. When using "the entire Python program", the documentation refers to the whole process.

以下程序可以帮助您了解守护程序线程和常规线程之间的区别:

The following program can help understand the difference between daemon thread and regular thread:

import sys
import time
import threading

class WorkerThread(threading.Thread):

    def run(self):
        while True:
            print 'Working hard'
            time.sleep(0.5)

def main(args):
    use_daemon = False
    for arg in args:
        if arg == '--use_daemon':
            use_daemon = True
    worker = WorkerThread()
    worker.setDaemon(use_daemon)
    worker.start()
    time.sleep(1)
    sys.exit(0)

if __name__ == '__main__':
    main(sys.argv[1:])

如果使用'--use_daemon'执行该程序,您将看到该程序仅打印少量的Working hard行.没有此标志,即使主线程完成,程序也不会终止,并且程序将打印Working hard行,直到被杀死为止.

If you execute this program with the '--use_daemon', you will see that the program will only print a small number of Working hard lines. Without this flag, the program will not terminate even when the main thread finishes, and the program will print Working hard lines until it is killed.

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

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