多线程与多进程 概述

使用多进程和多线程编程,可以同时处理多个任务,充分使用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方法的子进程终止后再往下执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值