首頁  >  問答  >  主體

coroutine - 关于python中的协程的变量问题

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

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中文网2741 天前373

全部回覆(1)我來回復

  • 阿神

    阿神2017-04-18 09:58:00

    python的協程是偽並發,並不是真正意義上的並發。真正在處理中的協成只能是一個,一個處理其他的都處於堵塞狀態。所以不會出現錯亂狀況。這是我的一知半解。 。

    回覆
    0
  • 取消回覆