python的多线程与多协程

单进程多线程

通过 threading 建立多个线程,并通过 queue 进行数据的维护。


from threading import Thread
from queue import Queue
import time

q = Queue()

def run():
    while True:
        msg = q.get()
        print(msg)
        time.sleep(1)
        q.task_done()

for i in range(10):
    q.put(i)

for i in range(3):
    t = Thread(target=run)
    t.setDaemon(True) # 队列没数据,主程序退出
    t.start()

q.join() # 队列无数据后,主程序退出

单进程多协程

通过 async 建立多个协程

当某个协程阻塞,会切换执行其他协程。


import time
import asyncio

async def SleepTime(ts):
    if ts == 3:
        await asyncio.sleep(10) #当ts等于3的时候,让挂起的时间为10s,其他的按正常挂起,验证协程时间。
    else:
        await asyncio.sleep(ts)

async def main(loop):
    tasks = []
    for i in range(6):
        print("time begin %s"%i)
        tasks.append(loop.create_task(SleepTime(i))) #相当于开启了一个线程
        print("sleep time end %s"%i)
        print("*********************")
    await asyncio.wait(tasks) #等待所有的任务完成。

if __name__ == "__main__":
    # main()
    print("begin test")
    tb = time.time()
    print(tb) #记录当前时间
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main(loop))
    loop.close()
    print(time.time()-tb) #记录结束时间
    print("end")

参考:

python async 使用,介绍_呱呱吖的博客-CSDN博客_async python

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值