Python 3 中的多线程

线程是独立执行或由操作系统调度的程序或进程的最小单元。在计算机系统中,操作系统通过将进程划分为线程来实现多任务处理。线程是一个轻量级的进程,它确保进程在系统上独立执行。在 Python 3 中,当多个处理器在一个程序上运行时,每个处理器同时运行以分别执行其任务。

Python 多线程

多线程是 Python 编程中的一种线程技术,通过在 CPU 的帮助下在线程之间快速切换来并发运行多个线程(称为上下文切换)。此外,它允许与进程内的主线程共享其数据空间,这比单独的进程更容易与其他线程共享信息和通信。多线程旨在同时执行多个任务,这提高了性能、速度并改善了应用的呈现。

注意:Python 全局解释器锁(GIL)允许一次运行一个线程,即使机器有多个处理器。

Python 中多线程的好处

以下是用 Python 创建多线程应用的好处,如下所示:

  1. 它保证了计算机系统资源的有效利用。
  2. 多线程应用响应速度更快。
  3. 它与子线程(子线程)共享资源及其状态,这使得它更加经济。
  4. 由于相似性,它使多进程器体系结构更加有效。
  5. 它通过同时执行多个线程来节省时间。
  6. 系统不需要太多内存来存储多个线程。

Python 中何时使用多线程?

这是一种非常有用的技术,可以节省时间并提高应用的性能。多线程允许程序员将应用任务划分为子任务,并在程序中同时运行它们。它允许线程与同一个处理器通信并共享资源,如文件、数据和内存。此外,它提高了用户继续运行程序的响应能力,即使应用的一部分太长或被阻塞。

Python 中如何实现多线程?

Python 中用于处理线程的多线程主要有两个模块。

  1. 线程模块
  2. 线程模块

线程模块

从 Python 3 开始,指定为过时,只能用支持向后兼容的 _thread 访问。

语法:


thread.start_new_thread ( function_name, args[, kwargs] )

要在 Python 中实现线程模块,我们需要导入一个线程模块,然后通过用变量设置目标来定义一个执行某个动作的函数。

螺纹 py


import thread # import the thread module
import time # import time module

def cal_sqre(num): # define the cal_sqre function
    print(" Calculate the square root of the given number")
    for n in num: 
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(' Square is : ', n * n)

def cal_cube(num): # define the cal_cube() function
    print(" Calculate the cube of  the given number")
    for n in num: 
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(" Cube is : ", n * n *n)

arr = [4, 5, 6, 7, 2] # given array

t1 = time.time() # get total time to execute the functions
cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function

print(" Total time taken by threads is :", time.time() - t1) # print the total time

输出:

Calculate the square root of the given number
 Square is:  16
 Square is:  25
 Square is:  36
 Square is:  49
 Square is:  4
 Calculate the cube of the given number
 Cube is:  64
 Cube is:  125
 Cube is:  216
 Cube is:  343
 Cube is:  8
 Total time taken by threads is: 3.005793809890747

线程模块

线程模块是多线程的高级实现,用于在 Python 中部署应用。要使用多线程,我们需要在 Python 程序中导入线程模块。

螺纹分类方法

| 方法 | 描述 |
| start() | start()方法用于启动线程的活动。它只为每个线程调用一次,这样线程的执行就可以开始了。 |
| 运行() | run()方法用于定义线程的活动,并且可以被扩展线程类的类覆盖。 |
| join() | join()方法用于阻止另一个代码的执行,直到线程终止。 |

按照下面给出的步骤在 Python 多线程中实现线程模块:

1。导入穿线模块

通过导入穿线模块创建新的穿线,如图所示。

语法:


import threading

一个线程模块由一个线程类组成,这个类被实例化来创建一个 Python 线程。

2。线程参数的声明:它包含目标函数、参数和 kwargs 作为 Thread() 类中的参数。

  • 目标:定义线程执行的函数名。
  • 参数:定义传递给目标函数名的参数。

例如:


import threading
def print_hello(n):
print("Hello, how old are you ", n)
t1 = threading.Thread( target = print_hello, args =(18, ))

在上面的代码中,我们调用了 print_hello() 函数作为目标参数。 print_hello() 包含一个参数 n ,传递给 args 参数。

3。启动新线程:要在 Python 多线程中启动线程,请调用线程类的对象。对于每个线程对象,可以调用 start()方法一次;否则,它会引发异常错误。

语法:


t1.start()
t2.start()

4。Join 方法:是线程类中使用的 join()方法,用于暂停主线程的执行,等待线程对象的完全执行。线程对象完成后,开始执行 Python 中的主线程。

连接方法. py


import threading
def print_hello(n):
    Print("Hello, how old are you? ", n)
T1 = threading.Thread( target = print_hello, args = (20, ))
T1.start()
T1.join()
Print("Thank you")

输出:

Hello, how old are you? 20
Thank you

执行上述程序时,join()方法会暂停主线程的执行,并等待直到线程 t1 完全执行。一旦 t1 成功执行,主线程就开始执行。

注意:如果我们不使用 join()方法,解释器可以在 Python 程序中执行任何 print 语句。一般来说,它执行第一个 print 语句,因为解释器从程序开始就执行代码行。

5。在 Python 中同步线程

这是一种线程同步机制,确保没有两个线程可以同时执行程序中的特定段来访问共享资源。这种情况可以称为临界区。我们使用竞争条件来避免临界区条件,在临界区条件中,两个线程不会同时访问资源。

让我们编写一个程序来使用 Python 多线程中的线程模块。

穿线. py


import time # import time module
import threading
from threading import *
def cal_sqre(num): # define a square calculating function
    print(" Calculate the square root of the given number")
    for n in num: # Use for loop 
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(' Square is : ', n * n)

def cal_cube(num): # define a cube calculating function
    print(" Calculate the cube of  the given number")
    for n in num: # for loop
        time.sleep(0.3) # at each iteration it waits for 0.3 time
        print(" Cube is : ", n * n *n)

ar = [4, 5, 6, 7, 2] # given array

t = time.time() # get total time to execute the functions
#cal_cube(ar)
#cal_sqre(ar)
th1 = threading.Thread(target=cal_sqre, args=(ar, ))
th2 = threading.Thread(target=cal_cube, args=(ar, ))
th1.start()
th2.start()
th1.join()
th2.join()
print(" Total time taking by threads is :", time.time() - t) # print the total time
print(" Again executing the main thread")
print(" Thread 1 and Thread 2 have finished their execution.")

输出:

Calculate the square root of the given number
 Calculate the cube of the given number
 Square is:  16
 Cube is:  64
 Square is:  25
 Cube is:  125
 Square is:  36
 Cube is:  216
 Square is:  49
 Cube is:  343
 Square is:  4
 Cube is:  8
 Total time taken by threads is: 1.5140972137451172
 Again executing the main thread
 Thread 1 and Thread 2 have finished their execution.

原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/270458.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-16 13:37
下一篇 2024-12-16 13:37

相关推荐

  • Python周杰伦代码用法介绍

    本文将从多个方面对Python周杰伦代码进行详细的阐述。 一、代码介绍 from urllib.request import urlopen from bs4 import Bea…

    编程 2025-04-29
  • 如何查看Anaconda中Python路径

    对Anaconda中Python路径即conda环境的查看进行详细的阐述。 一、使用命令行查看 1、在Windows系统中,可以使用命令提示符(cmd)或者Anaconda Pro…

    编程 2025-04-29
  • Python中引入上一级目录中函数

    Python中经常需要调用其他文件夹中的模块或函数,其中一个常见的操作是引入上一级目录中的函数。在此,我们将从多个角度详细解释如何在Python中引入上一级目录的函数。 一、加入环…

    编程 2025-04-29
  • Python列表中负数的个数

    Python列表是一个有序的集合,可以存储多个不同类型的元素。而负数是指小于0的整数。在Python列表中,我们想要找到负数的个数,可以通过以下几个方面进行实现。 一、使用循环遍历…

    编程 2025-04-29
  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • Python程序需要编译才能执行

    Python 被广泛应用于数据分析、人工智能、科学计算等领域,它的灵活性和简单易学的性质使得越来越多的人喜欢使用 Python 进行编程。然而,在 Python 中程序执行的方式不…

    编程 2025-04-29
  • python强行终止程序快捷键

    本文将从多个方面对python强行终止程序快捷键进行详细阐述,并提供相应代码示例。 一、Ctrl+C快捷键 Ctrl+C快捷键是在终端中经常用来强行终止运行的程序。当你在终端中运行…

    编程 2025-04-29
  • Python清华镜像下载

    Python清华镜像是一个高质量的Python开发资源镜像站,提供了Python及其相关的开发工具、框架和文档的下载服务。本文将从以下几个方面对Python清华镜像下载进行详细的阐…

    编程 2025-04-29
  • Python字典去重复工具

    使用Python语言编写字典去重复工具,可帮助用户快速去重复。 一、字典去重复工具的需求 在使用Python编写程序时,我们经常需要处理数据文件,其中包含了大量的重复数据。为了方便…

    编程 2025-04-29
  • 蝴蝶优化算法Python版

    蝴蝶优化算法是一种基于仿生学的优化算法,模仿自然界中的蝴蝶进行搜索。它可以应用于多个领域的优化问题,包括数学优化、工程问题、机器学习等。本文将从多个方面对蝴蝶优化算法Python版…

    编程 2025-04-29

发表回复

登录后才能评论