uasyncio lock not working

The official PYBD running MicroPython, and its accessories.
Target audience: Users with a PYBD
Post Reply
goldimman
Posts: 1
Joined: Wed Feb 17, 2021 12:18 pm

uasyncio lock not working

Post by goldimman » Wed Feb 17, 2021 12:20 pm

Hi

I am running on: MicroPython v1.14-56-g5cb91afb9 on 2021-02-17; PYBD-SF6W with STM32F767IIK

and the below prints False. Any ideas how to get this working?

import uasyncio
l = uasyncio.Lock()
l.acquire()
print("locked ", l.locked())

Device path COM10
Quit: Ctrl+] | Stop program: Ctrl+C | Reset: Ctrl+D
Type 'help()' (without the quotes) then press ENTER.
locked False
MicroPython v1.14-56-g5cb91afb9 on 2021-02-17; PYBD-SF6W with STM32F767IIK
Type "help()" for more information.
>>>
>>>
>>>

User avatar
jimmo
Posts: 2262
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: uasyncio lock not working

Post by jimmo » Thu Feb 18, 2021 12:35 am

goldimman wrote:
Wed Feb 17, 2021 12:20 pm
and the below prints False. Any ideas how to get this working?
You need to use lock within an asyncio-based program.

In this case, the acquire method on Lock is a coroutine, i.e. you need to "await" it.

So:

Code: Select all

import uasyncio as asyncio

lock = asyncio.Lock()

async def my_task():
  await lock.acquire()
  print("locked", lock.locked())

asyncio.run(my_task())
If you call a coroutine without awaiting it, the code will not run.

User avatar
pythoncoder
Posts: 5101
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: uasyncio lock not working

Post by pythoncoder » Thu Feb 18, 2021 8:24 am

See example code here.
Peter Hinch

Post Reply