coroutine - 关于python中的协程的变量问题
PHP中文网
PHP中文网 2017-04-18 09:56:00
0
1
409

对于线程来说,可能会有线程安全的问题,比如

total = 0

def do_something():
    global total
    # do something else
    total += 1

这个函数,对全局变量total自增,在多线程的情况下,运行十万次,最终total的结果可能不是100000

而对于单线程中的多个协程来说,可能会出现这种情况吗,比如

total = 0

async def do_something():
    global total
    # do something else
    total += 1
    
def test():
    while True:
        # do something
        asyncio.ensure_future(do_something())

当do_something()在协程中运行十万次时,total的最终结果一定是十万吗?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(1)
阿神

Python's coroutines are pseudo-concurrency, not concurrency in the true sense. There can only be one synergy that is actually being processed, and if one is processing the others, they are all in a blocked state. So there will be no confusion. This is my partial understanding. .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template