Python多线程编程---(1)threading 模块 Thread 类

全文参考:https://blog.csdn.net/briblue/article/details/85101144

最近看了下团队自动化测试用例的代码,里面有涉及并行处理的逻辑,主要是基于python的threading 模块来实现的,但运行结果出现了一些奇怪的现象,花了一天的时候改去改来没问题定位到原因,归根结底还是自己对多线程这一块不熟悉,因此注备花点时间学习下python的threading 模块用法。

一般并发的手段有采用多进程和多线程,但线程比进程更轻量化,系统开销一般也更低,所以大家更倾向于用多线程的方式处理并发的情况。

Python 提供多线程编程的方式,Python 实现多线程编程需要借助于 threading 模块,下面的示例基于Python3来实现。

引用方式如下,threading 模块中最核心的内容是 Thread 这个类。

import threading

我们要创建 Thread 对象,然后让它们运行,每个 Thread 对象代表一个线程,在每个线程中我们可以让程序处理不同的任务,这就是多线程编程。值得注意的是,程序运行时默认就是在主线程上。

创建 Thread 对象有 2 种手段

(1)直接创建 Thread ,将一个 callable 对象从类的构造器传递进去,这个 callable 就是回调函数,用来处理任务。
编写一个自定义类继承 Thread,然后复写 run() 方法,在 run() 方法中编写任务处理代码,然后创建这个 Thread 的子类。

(2)编写一个自定义类继承 Thread,然后复写 run() 方法,在 run() 方法中编写任务处理代码,然后创建这个 Thread 的子类。

1. 直接创建 Thread 对象

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

示例代码:

import threading
import time


def test():
    for index in range(5):
        print(threading.current_thread().name + ' test ', index)
        time.sleep(1)


thread = threading.Thread(target=test)
thread.start() # 启动线程

for i in range(5):
    print(threading.current_thread().name + ' main ', i)
    time.sleep(1)


 

 

你可能感兴趣的:(Python)