python多线程多进程协程_python 多进程,多线程,协程

在我们实际编码中,会遇到一些并行的任务,因为单个任务无法最大限度的使用计算机资源。使用并行任务,可以提高代码效率,最大限度的发挥计算机的性能。python实现并行任务可以有多进程,多线程,协程等方式。

进程,线程,协程

进程

进程是程序运行的基本单位,资源分配和独立运行的基本单位。

多进程实现并行任务代码:

import multiprocessing

import time

def test(interval):

n = 5

while n > 0:

time.sleep(interval)

n -= 1

if __name__ == "__main__":

p = multiprocessing.Process(target = test, args = (3,))

p1 = multiprocessing.Process(target = test, args = (3,))

p2 = multiprocessing.Process(target = test, args = (3,))

p3 = multiprocessing.Process(target = test, args = (3,))

p.start()

p1.start()

p2.start()

p3.start()

print("p.pid:", p.pid)

print("p1.pid:", p.pid)

print("p2.pid:", p.pid)

print("p3.pid:", p.pid)

执行结果

线程

通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程可以利用进程所拥有的资源,在引入线程的操作系统中,通常都是把进程作为分配资源的基本单位,而把线程作为独立运行和独立调度的基本单位,由于线程比进程更小,基本上不拥有系统资源,故对它的调度所付出的开销就会小得多,能更高效的提高系统多个程序间并发执行的程度。

多线程实现并行(这里采用线程池):

import threadpool

import threading

import time

task_pool = threadpool.ThreadPool(10)

def func(t):

print(f'sleep {t} s. {threading.currentThread()}')

time.sleep(t)

print(f'{threading.currentThread()} have Done!!')

args = [5 for i in range(5)]

rs = threadpool.makeRequests(func, args)

for req in rs:

task_pool.putRequest(req)

task_pool.wait()

运行结果

协程

协程,又称微线程,是为非抢占式多任务产生子程序的计算机程序组件,协程允许不同入口点在不同位置暂停或开始执行程序。

简单来讲,就是我们可以在执行的时候停下来执行另一子程序,当子程序执行完之后在此切换回来。并且是非阻塞的,也就意味着我们可以同时执行多个协程。

也因为协程是单线程,所以我们切换所需要的开销最小,效率最高。

实现代码:

import asyncio

import threading

import random

import time

async def test(t, count):

print(f'sleep {t} s. {threading.currentThread()}')

# 使用asyncio.sleep() 而不用time.sleep() 是因为time.sleep()回挂起整个线程,

# 而协程是基于单线程的,所以会block住

#time.sleep(4)

r = await asyncio.sleep(t)

return t

def main():

print("start ..")

start = time.time()

loop = asyncio.get_event_loop()

tasks = [test(1, i) for i in range(5)]

loop.run_until_complete(asyncio.wait(tasks))

loop.close()

print(f'{time.time()-start}, finall {c}')

return c

if __name__ == '__main__':

x = main()

运行结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值