首页 > 编程知识 正文

Python 3 中的多线程

时间:2023-11-25 15:30:10 阅读:309209 作者:VVMS

线程是独立执行或由操作系统调度的程序或进程的最小单元。在计算机系统中,操作系统通过将进程划分为线程来实现多任务处理。线程是一个轻量级的进程,它确保进程在系统上独立执行。在 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.

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。