分享

python多线程结束线程...

 馆藏室101 2022-03-15

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 threading module. Python multiprocessing is one of the similar module that we looked into sometime back.

Python线程模块用于在python程序中实现多线程。 在本课程中,我们将研究Thread和python threading模块的不同功能。 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:

有关线程的几点注意事项:

  • Threads exists inside a process. 线程存在于进程内部。
  • Multiple threads can exist in a single process. 一个进程中可以存在多个线程。
  • Threads in same process share the state and memory of the parent process. 同一进程中的线程共享父进程的状态和内存。

This was just a quick overview of Threads in general. This post will mainly focus on the threading module in Python.

这只是一般的Thread的快速概述。 这篇文章将主要关注Python中的threading模块。

Python线程 (Python threading)

Let us introduce python threading module with a nice and simple example:

让我们通过一个简单的好例子介绍python threading模块:

  1. import time
  2. from threading import Thread
  3. def sleepMe(i):
  4. print("Thread %i going to sleep for 5 seconds." % i)
  5. time.sleep(5)
  6. print("Thread %i is awake now." % i)
  7. for i in range(10):
  8. th = Thread(target=sleepMe, args=(i, ))
  9. th.start()

When we run this script, the following will be the output:

Python Threading Example, Python multithreading example

当我们运行此脚本时,将输出以下内容:

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 module and build up the program to show different threading functions.

我们将重用使用threading模块编写的最后一个简单程序,并构建该程序以显示不同的线程功能。

threading.active_count() (threading.active_count())

This function returns the number of threads currently in execution. Let us modify the last script’s sleepMe(...) function. Our new script will look like:

该函数返回当前正在执行的线程数。 让我们修改最后一个脚本的sleepMe(...)函数。 我们的新脚本如下所示:

  1. import time
  2. import threading
  3. from threading import Thread
  4. def sleepMe(i):
  5. print("Thread %i going to sleep for 5 seconds." % i)
  6. time.sleep(5)
  7. print("Thread %i is awake now." % i)
  8. for i in range(10):
  9. th = Thread(target=sleepMe, args=(i, ))
  10. th.start()
  11. print("Current Thread count: %i." % threading.active_count())

This time, we will have a new output showing how many threads are active. Here is the output:

Python multithreading example, python threading active count

这次,我们将有一个新的输出,显示有多少线程处于活动状态。 这是输出:

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:

该函数返回正在执行的当前线程。 使用此方法,我们可以对获得的线程执行特定的操作。 让我们修改脚本以立即使用此方法:

  1. import time
  2. import threading
  3. from threading import Thread
  4. def sleepMe(i):
  5. print("Thread %s going to sleep for 5 seconds." % threading.current_thread())
  6. time.sleep(5)
  7. print("Thread %s is awake now.\n" % threading.current_thread())
  8. #Creating only four threads for now
  9. for i in range(4):
  10. th = Thread(target=sleepMe, args=(i, ))
  11. th.start()

The output of the above script will be:

Python Threading Current Thread

上面脚本的输出将是:

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:

该函数返回该程序的主线程。 可以从该线程中产生更多线程。 让我们看一下这个脚本:

  1. import threading
  2. print(threading.main_thread())

Now, let’s run this script:

Python Main Thread

现在,让我们运行以下脚本:

As shown in the image, it is worth noticing that the main_thread() function was only introduced in Python 3. So take care that you use this function only when using Python 3+ versions.

如图所示,值得注意的是main_thread()函数仅在Python 3中引入。因此请注意,仅在使用Python 3+版本时才使用此函数。

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:

此函数返回所有活动线程的列表。 它很容易使用。 让我们编写一个脚本来使用它:

  1. import threading
  2. for thread in threading.enumerate():
  3. print("Thread name is %s." % thread.getName())

Now, let’s run this script:

Python Threading Enumerate

现在,让我们运行以下脚本:

We were having only Main thread when we executed this script, hence the output.

执行此脚本时只有主线程,因此只有输出。

threading.Timer() (threading.Timer())

This function of threading module is used to create a new Thread and letting it know that it should only start after a specified time. Once it starts, it should call the specified function. Let’s study it with an example:

threading模块的此功能用于创建新的线程,并使其仅在指定时间后启动。 一旦启动,它应该调用指定的函数。 让我们用一个例子来研究它:

  1. import threading
  2. def delayed():
  3. print("I am printed after 5 seconds!")
  4. thread = threading.Timer(3, delayed)
  5. thread.start()

Now, let’s run this script:

Python Threading Timer

现在,让我们运行以下脚本:

Python多线程 (Python Multithreading)

In this post, we saw some functions in the threading module in Python and how it provides convenient methods to control Threads in a multithreaded environment.

在这篇文章中,我们看到了Python threading模块中的一些功能,以及它如何提供方便的方法来控制多线程环境中的线程。

Reference: API Doc

参考: API文档

翻译自: https://www./17290/python-threading-multithreading

python多线程结束线程

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多