python多线程结束线程 Python threading module is used to implement multithreading in python programs. In this lesson, we will study about Thread and different functions of python Python线程模块用于在python程序中实现多线程。 在本课程中,我们将研究Thread和python 什么是线程? (What is a Thread?)In Computer Science, threads are defined as the smallest unit of work which is scheduled to be done by an Operating System. 在《计算机科学》中,线程被定义为计划由操作系统完成的最小工作单元。 Some points to consider about Threads are: 有关线程的几点注意事项:
This was just a quick overview of Threads in general. This post will mainly focus on the 这只是一般的Thread的快速概述。 这篇文章将主要关注Python中的 Python线程 (Python threading)Let us introduce python 让我们通过一个简单的好例子介绍python
When we run this script, the following will be the output: 当我们运行此脚本时,将输出以下内容: When you run this program, the output might be different as parallel threads doesn’t have any defined order of their life. 当您运行此程序时,输出可能会有所不同,因为并行线程没有生命周期的任何已定义顺序。 Python线程功能 (Python threading functions)We will reuse the last simple program we wrote with 我们将重用使用 threading.active_count() (threading.active_count())This function returns the number of threads currently in execution. Let us modify the last script’s 该函数返回当前正在执行的线程数。 让我们修改最后一个脚本的
This time, we will have a new output showing how many threads are active. Here is the output: 这次,我们将有一个新的输出,显示有多少线程处于活动状态。 这是输出: Note that active thread count, after all 10 threads has started is not 10 but 11. This is because it also counts the main thread inside from other 10 threads were spawned. 请注意,在所有10个线程启动之后,活动线程数不是10而是11 。 这是因为它还计算生成的其他10个线程中的主线程。 threading.current_thread() (threading.current_thread())This function returns the current thread in execution. Using this method, we can perform particular actions with the obtained thread. Let us modify our script to use this method now: 该函数返回正在执行的当前线程。 使用此方法,我们可以对获得的线程执行特定的操作。 让我们修改脚本以立即使用此方法:
The output of the above script will be: 上面脚本的输出将是: threading.main_thread() (threading.main_thread())This function returns the main thread of this program. More threads can be spawned form this thread. Let us see this script: 该函数返回该程序的主线程。 可以从该线程中产生更多线程。 让我们看一下这个脚本:
Now, let’s run this script: 现在,让我们运行以下脚本: As shown in the image, it is worth noticing that the 如图所示,值得注意的是 threading.enumerate() (threading.enumerate())This function returns a list of all active threads. It is easy to use. Let us write a script to put it in use: 此函数返回所有活动线程的列表。 它很容易使用。 让我们编写一个脚本来使用它:
Now, let’s run this script: 现在,让我们运行以下脚本: We were having only Main thread when we executed this script, hence the output. 执行此脚本时只有主线程,因此只有输出。 threading.Timer() (threading.Timer())This function of
Now, let’s run this script: 现在,让我们运行以下脚本: Python多线程 (Python Multithreading)In this post, we saw some functions in the 在这篇文章中,我们看到了Python Reference: API Doc 参考: API文档 python多线程结束线程 |
|
来自: 馆藏室101 > 《python笔记》