CPython implementation detail: 在 CPython 中,由于存在全局解释器锁, 同一时刻只有一个线程可以执行 Python 代码(虽然某些性能导向的库可能会去除此限制)。 如果你想让你的应用更好地利用多核心计算机的计算资源,推荐你使用multiprocessing或concurrent.futures.ProcessPoolExecutor但是,如果你想要同时运行多个 I/O 密集型任务,则多线程仍然是一个合适的模型
一、多线程Threading模块的使用
值得注意的是,程序运行时默认就是在主线程上
创建 Thread 对象有 2 种手段。
直接创建 Thread ,将一个 callable 对象从类的构造器传递进去,这个 callable 就是回调函数,用来处理任务。
编写一个自定义类继承 Thread,然后复写 run() 方法,在 run() 方法中编写任务处理代码,然后创建这个 Thread 的子类。
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
Thread 的构造方法中,最重要的参数是 target,所以我们需要将一个 callable 对象赋值给它,线程才能正常运行。
如果要让一个 Thread 对象启动,调用它的 start() 方法就好了。
1.多线程在自动化测试中运用较为广泛,一起来看下:
Thread(target="",name="",args="",kwargs="")
参数1:target:可执行目标
参数2:name:线程的名字默认Thread-N
参数3:args/kwargs:目标参数
三个常用的参数如上所示,那么接下来通过实例来更深入的了解一下吧。
2.来看一下正常运行的代码:
import threading
import time
def one():
for i in range(5):
print("起立 , 第%s次 "%(i))
time.sleep(0.5)
def two():
for i in range(5):
print("坐下 , 第%s次"%(i))
time.sleep(0.5)
one()
two()
输出:
如上所示,没有运用到多线程的代码,会按照从上往下的顺序依次执行,打印如上图。
3.在来看一下加入多线程的代码运行:
import threading
import time
def one():
for i in range(5):
print("起立 , 第%s次 "%(i))
time.sleep(0.5)
def two():
for i in range(5):
print("坐下 , 第%s次"%(i))
time.sleep(0.5)
if __name__ =="__main__":
test_one = threading.Thread(target=one)
test_two = threading.Thread(target=two)
test_one.start()
test_two.start()
print("主线程执行完毕")
输出:
如上所示,加入了多线程的代码,会同步执行函数,通过加入多线程和不加入多线程代码执行的实例,大家应该对于多线程有了更深入的一些了解。
二、总结
由此可见,没有加多线程的代码从上往下运行,加了多线程的代码,3个同时进行,输出“主线程执行完毕”,另外两个子线程去执行one()和 two() 线程,从他们的执行速度来看,它们是同时在进行的。