对于线程来说,可能会有线程安全的问题,比如
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的最终结果一定是十万吗?
python的协程是伪并发,并不是真正意义上的并发。真正在处理中的协成只能是一个,一个处理其他的都处于堵塞状态。所以不会出现错乱情况。这是我的一知半解。。