资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

Python中的asyncio库-线程同步

今天就跟大家聊聊有关Python中的asyncio库-线程同步,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

我们提供的服务有:网站制作、做网站、微信公众号开发、网站优化、网站认证、禹州ssl等。为近千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的禹州网站制作公司

前面的代码都是异步的,就如sleep,需要用asyncio.sleep而不是阻塞的time.sleep,如果有同步逻辑,怎么利用asyncio实现并发呢?答案是用run_in_executor。在一开始我说过开发者创建 Future 对象情况很少,主要是用run_in_executor,就是让同步函数在一个执行器( executor)里面运行。

同步代码

def a():
    time.sleep(1)
    return 'A'
async def b():
    await asyncio.sleep(1)
    return 'B'
def show_perf(func):
    print('*' * 20)
    start = time.perf_counter()
    asyncio.run(func())
    print(f'{func.__name__} Cost: {time.perf_counter() - start}')
async def c1():
    loop = asyncio.get_running_loop()
    await asyncio.gather(
        loop.run_in_executor(None, a),
        b()
    )
In : show_perf(c1)
********************
c1 Cost: 1.0027242230000866

可以看到用run_into_executor可以把同步函数逻辑转化成一个协程,且实现了并发。这里要注意细节,就是函数a是普通函数,不能写成协程,下面的定义是错误的,不能实现并发:

async def a():
    time.sleep(1)
    return 'A'

因为 a 里面没有异步代码,就不要用async def来定义。需要把这种逻辑用loop.run_in_executor封装到协程:

async def c():
    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(None, a)

大家理解了吧?

loop.run_in_executor(None, a)这里面第一个参数是要传递concurrent.futures.Executor实例的,传递None会选择默认的executor:

In : loop._default_executor
Out: 

当然我们还可以用进程池,这次换个常用的文件读写例子,并且用:

async def c3():
    loop = asyncio.get_running_loop()
    with concurrent.futures.ProcessPoolExecutor() as e:
        print(await asyncio.gather(
            loop.run_in_executor(e, a),
            b()
        ))
In : show_perf(c3)
********************
['A', 'B']
c3 Cost: 1.0218078890000015

看完上述内容,你们对Python中的asyncio库-线程同步有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


名称栏目:Python中的asyncio库-线程同步
网站地址:http://cdkjz.cn/article/pppics.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220