使用多进程和多线程编程,可以同时处理多个任务,充分使用CPU性能,节约时间等。很多编程任务到最后都发展到需要同时处理多任务,就比如APP自动化测试,如果一个脚本一次只能在一台设备上测试APP,那就显得有些“低效”了,所以学习多线程和多进程也是很有必要的。以下的代码是作为一个示范,显示如何创建多线程以及多进程。
#进程,是系统进行资源分配和调度的基本单位,是操作系统结构的基础
#线程,有时被称为轻量级进程,是程序执行流的最小单元。线程是进程中的一个实体
#一个进程可以包含多个线程,但是线程不能包含多个进程
#进程和线程的区别在于,子进程和父进程有不同的代码和数据空间,而多个线程则共享数据空间,每个线程有自己的执行堆栈和程序计数器为其执行上下文
#多线程实践
import threading
from time import sleep,ctime
#定义好2个任务
def talk(content, count):
for i in range(count):
print(f'start to talk{content,ctime()}')
sleep(3)
def write(content,count):
for i in range(count):
print(f'start to write{content,ctime()}')
sleep(2)
threads = []
#创建好2个线程,并装载到线程列表里
t1 = threading.Thread(target=talk,args=('hello world',2))
threads.append(t1)
t2 = threading.Thread(target=write,args=('oh my god',2))
threads.append(t2)
if __name__ == '__main__':
for thread in threads:
thread.start()
for thread in threads:
thread.join() #join方法作用是主线程等待调用join方法的子线程终止后再往下执行
#多进程实践,基本原理和多线程相似,只是导入的模块不一样
import multiprocessing
from time import sleep,ctime
def talk(content, count):
for i in range(count):
print(f'start to talk{content,ctime()}')
sleep(3)
def write(content,count):
for i in range(count):
print(f'start to write{content,ctime()}')
sleep(2)
processes = []
p1 = multiprocessing.Process(target=talk,args=('hello world',3))
processes.append(p1)
p2 = multiprocessing.Process(target=write,args=('oh my god',3))
processes.append(p2)
if __name__ == '__main__':
for process in processes:
process.start()
for process in processes:
process.join() #join方法作用是主进程等待调用join方法的子进程终止后再往下执行