简体   繁体   中英

Can not modify global variable in an asynchronous function (coroutine) in python

I run this code in jupyter notebook(python 3.6.8). I expect the code to print 2 as the result, somehow it still prints 1. I want to know why.

import asyncio
x = 1

async def func():
    global x
    x = 2
    print(x)

await func()
print(x)

And the result is: 在此处输入图像描述

The jupyter notebook environment I am using is:

  • jupyter core : 4.6.3
  • jupyter-notebook : 6.1.4
  • qtconsole : 4.7.7
  • ipython : 7.16.1
  • ipykernel : 5.3.4
  • jupyter client : 6.1.7
  • jupyter lab : 2.2.9
  • nbconvert : 6.0.7
  • ipywidgets : 7.5.1
  • nbformat : 5.1.2
  • traitlets : 4.3.3

If you want to change a global variable in IPython coroutine you have to acquire the asyncio.Lock .

import asyncio

x = 1

async def func():
    global x
    lock = asyncio.Lock()
    await lock.acquire()
    x = 2
    lock.release()

await func()
print(x)  # 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM