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模块:

import time
from threading import Threaddef sleepMe(i):print("Thread %i going to sleep for 5 seconds." % i)time.sleep(5)print("Thread %i is awake now." % i)for i in range(10):th = Thread(target=sleepMe, args=(i, ))th.start()

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 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(...)函数。 我们的新脚本如下所示:

import time
import threading
from threading import Threaddef sleepMe(i):print("Thread %i going to sleep for 5 seconds." % i)time.sleep(5)print("Thread %i is awake now." % i)for i in range(10):th = Thread(target=sleepMe, args=(i, ))th.start()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:

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

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:

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

import time
import threading
from threading import Threaddef sleepMe(i):print("Thread %s going to sleep for 5 seconds." % threading.current_thread())time.sleep(5)print("Thread %s is awake now.\n" % threading.current_thread())#Creating only four threads for now
for i in range(4):th = Thread(target=sleepMe, args=(i, ))th.start()

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:

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

import threading
print(threading.main_thread())

Now, let’s run this script:

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

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:

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

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

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

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

Now, let’s run this script:

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

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.journaldev.com/17290/python-threading-multithreading

python多线程结束线程

python多线程结束线程_Python线程– Python多线程相关推荐

  1. python多线程队列处理_Python线程和队列使用的一点思考

    Python线程和队列使用的一点思考 1. 斗哥采访环节请问为什么要使用线程? 答:为了提高程序速度,代码效率呀. 请问为什么要使用队列? 答:个人认为队列可以保证线程安全,实现线程间的同步,比较稳. ...

  2. python多程优化_Python 基本功: 13. 多线程运算提速

    小编在前两天开通了一个 Python 金融的专栏,顺便用 TuShare 下载了几只 A股的数据,有兴趣的小伙伴可以去看一下: 多多教Python:Python 金融: TuShare API 获取股 ...

  3. python多线程实现方式_python中实现多线程有几种方式?

    我们都知道,代码编程不是固定的东西,而是非常灵活的内容,根据不同的内容,我们可以拓展出很多条内容,最终目的还是为了可以实现结果,给大家举例说明其中一个最常用的多线程吧~以及实现的几种方式. 1. 用函 ...

  4. python 线程_python 线程

    一.什么是线程 线程(英语:thread)是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线 ...

  5. python并发与并行_python多进程,多线程分别是并行还是并发

    匿名用户 1级 2017-09-30 回答 展开全部 并发和并行 你吃饭吃到一半,电话来了,你一直到吃完了以后才去接,这就说明你不支持并发也不支持并行. 你吃饭吃到一半,电话来了,你停了下来接了电话, ...

  6. python多线程控制暂停_python中的多线程编程与暂停、播放音频的结合

    我们都知道python中可以是threading模块实现多线程, 但是模块并没有提供暂停, 恢复和停止线程的方法, 一旦线程对象调用start方法后, 只能等到对应的方法函数运行完毕. 也就是说一旦s ...

  7. python基础主要内容_python基础—python的介绍

    编译器是把源程序的每一条语句都编译成机器语言,并保存成二进制文件,这样运行时计算机可以直接以机器语言来运行此程序,速度很快; 而解释器则是只在执行程序时,才一条一条的解释成机器语言给计算机来执行,所以 ...

  8. python 等号报错_Python学习----Python基础

    Python基础 一.数据类型和变量 1.在Python中,等号=是赋值语句,可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量. 例如: a =520# a是整数prin ...

  9. python作者龟叔_Python基础 — Python简介

    序言:未来是数据的世界,而python 是一门可以高效简洁处理数据的语言,博主打算花一些时间完成python学习的从0到1.以此相关系列博客作为一个记录. 1. Python简介 Python的发音与 ...

最新文章

  1. beta冲刺(2/7)
  2. 开发日记-20190708 关键词 读书笔记 《Perl语言入门》Day 5
  3. cisco IOS及配置的备份及升级
  4. 表之顺序结构和链式结构
  5. 大佬都在用的桑基图到底怎么做?告诉你个最简单的方法
  6. 实现strcmp库函数的功能
  7. OAuth:服务给第三方app授权的协议
  8. path:path在路由中的使用
  9. 用“谬论”指挥研究方向数十年,是谁让“老年痴呆”至今仍是绝症?
  10. iOS -- 音频播放、录音、视频播放、拍照、视频录制
  11. JQuery Ajax 解析
  12. Bailian4068 判断是否可以构成等差数列【字符串流+排序】
  13. cocos2d Labels and Fonts 标签和字体
  14. 2018年个人的一些简单预测
  15. 计算机软件研究方法与技术路线,项目的研究方法与技术路线
  16. 数据分析--数据预处理
  17. nginx反向代理打印日志_Nginx 反向代理 log 显示真IP地址
  18. 3.19 使用钢笔工具绘制一枚诱人的梨子 [Illustrator CC教程]
  19. Oracle Rac 添加节点测试笔记
  20. 透明、反光材质护肤品拍摄技巧

热门文章

  1. [转载] python oct_Python oct()
  2. [转载] Python性能优化技巧总结
  3. verilog 中生成块的相关知识
  4. Apache日志配置详解(rotatelogs LogFormat)
  5. 论文学习: Journaling of Journal is (almost) Free 未整理
  6. ajax+MultipartFile上传文件到本地
  7. MyEclipse的html页面 design视图中 关闭可视化界面
  8. 内存cgroup---CGroup中参数由来篇
  9. MYSQL—— 启动MYSQL 57 报错“The service MYSQL57 failed the most recent........等”的问题解决方式!...
  10. BZOJ3678: wangxz与OJ