python中asyncio与多线程结合

参考:https://blog.csdn.net/qq_37674086/article/details/113884580

multithreading+asyncio总结

第一步:定义需要异步执行的一系列操作,及一系列协程函数;

第二步:在主线程中定义一个新的线程,然后在新线程中产生一个新的事件循环;

第三步:在主线程中,通过asyncio.run_coroutine_threadsafe(coroutine,loop)这个方法,将一系列异步方法注册到新线程的loop里面去,这样就是新线程负责事件循环的执行。

'''
Description: 
Author: pdh
Date: 2020-10-14 17:07:42
LastEditors: pdh
LastEditTime: 2020-11-06 18:25:58
FilePath: \pyserver\websocket_server.py
'''
# coding=utf-8

import websockets
import threading
import asyncio
import datetime

gLock = threading.Lock()


def getTime():
    global gLock
    gLock.acquire()
    now = datetime.datetime.now()
    tm = ":".join([
        str(now.day).zfill(2),
        str(now.hour).zfill(2),
        str(now.minute).zfill(2),
        str(now.second).zfill(2),
        str(now.microsecond)
    ])
    gLock.release()
    return tm


def log(*msg):

    tm = getTime()
    global gLock
    gLock.acquire()
    # 数组前面加参数,代表把数组拆分成多个逗号分割的变量,类似js中的展开符号...
    text = ",".join([tm, "  ", *msg])
    print(text)
    gLock.release()


class CListen(threading.Thread):
    def __init__(self, loop):
        threading.Thread.__init__(self)
        self.mLoop = loop

    def run(self):
        asyncio.set_event_loop(self.mLoop)  # 在新线程中开启一个事件循环
        log("prepare run_for")
        self.mLoop.run_forever()
        log("end run_for")  # 跑不到这里


async def callLater(name, seconds):
    log("callLater start {}".format(name))
    count = 0
    while (count < 3):
        log("callLater middle {}  {}".format(name, count))
        count += 1
        await asyncio.sleep(seconds)
    log("callLater end {}  ".format(name))


if __name__ == '__main__':
    # websockets.serve()

    newLoop = asyncio.new_event_loop()
    listen = CListen(newLoop)
    listen.setDaemon(True)
    listen.start()

    asyncio.run_coroutine_threadsafe(callLater("one", 1), newLoop)
    asyncio.run_coroutine_threadsafe(callLater("two", 1), newLoop)
    asyncio.run_coroutine_threadsafe(callLater("three", 1), newLoop)
    while (True):
        line = input("输入q退出:")
        if (line == 'q'):
            break

结果:

输入q退出:09:15:12:38:710933,  ,prepare run_for
09:15:12:38:712932,  ,callLater start one
09:15:12:38:713952,  ,callLater middle one  0
09:15:12:38:714930,  ,callLater start two
09:15:12:38:714930,  ,callLater middle two  0
09:15:12:38:715930,  ,callLater start three
09:15:12:38:716929,  ,callLater middle three  0
09:15:12:39:703121,  ,callLater middle one  1
09:15:12:39:704092,  ,callLater middle two  1
09:15:12:39:705089,  ,callLater middle three  1
09:15:12:40:706462,  ,callLater middle one  2
09:15:12:40:708427,  ,callLater middle two  2
09:15:12:40:712408,  ,callLater middle three  2
09:15:12:41:713967,  ,callLater end one
09:15:12:41:714920,  ,callLater end two
09:15:12:41:718914,  ,callLater end three

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值