extmod/uasyncio: Add clear method to ThreadSafeFlag.

This is useful in situations where the ThreadSafeFlag is reused and needs
to be cleared of any previous, unwanted event.

For example, clear the flag at the start of an operation, trigger the
operation (eg an I2C write), then (a)wait for an external event to set the
flag (eg a pin IRQ).  Further events may trigger the flag again but these
are unwanted and should be cleared before the next cycle starts.
pull/9051/head
Ned Konz 2021-09-01 10:48:15 -07:00 zatwierdzone przez Damien George
rodzic cf90e24335
commit 5543b2a9cc
4 zmienionych plików z 41 dodań i 2 usunięć

Wyświetl plik

@ -153,9 +153,14 @@ class ThreadSafeFlag
.. method:: ThreadSafeFlag.set() .. method:: ThreadSafeFlag.set()
Set the flag. If there is a task waiting on the event, it will be scheduled Set the flag. If there is a task waiting on the flag, it will be scheduled
to run. to run.
.. method:: ThreadSafeFlag.clear()
Clear the flag. This may be used to ensure that a possibly previously-set
flag is clear before waiting for it.
.. method:: ThreadSafeFlag.wait() .. method:: ThreadSafeFlag.wait()
Wait for the flag to be set. If the flag is already set then it returns Wait for the flag to be set. If the flag is already set then it returns

Wyświetl plik

@ -36,7 +36,7 @@ class Event:
# MicroPython-extension: This can be set from outside the asyncio event loop, # MicroPython-extension: This can be set from outside the asyncio event loop,
# such as other threads, IRQs or scheduler context. Implementation is a stream # such as other threads, IRQs or scheduler context. Implementation is a stream
# that asyncio will poll until a flag is set. # that asyncio will poll until a flag is set.
# Note: Unlike Event, this is self-clearing. # Note: Unlike Event, this is self-clearing after a wait().
try: try:
import uio import uio
@ -52,6 +52,9 @@ try:
def set(self): def set(self):
self._flag = 1 self._flag = 1
def clear(self):
self._flag = 0
async def wait(self): async def wait(self):
if not self._flag: if not self._flag:
yield core._io_queue.queue_read(self) yield core._io_queue.queue_read(self)

Wyświetl plik

@ -75,5 +75,25 @@ async def main():
print("wait task") print("wait task")
await t await t
# Flag set, cleared, and set again.
print("----")
print("set event")
flag.set()
print("yield")
await asyncio.sleep(0)
print("clear event")
flag.clear()
print("yield")
await asyncio.sleep(0)
t = asyncio.create_task(task(4, flag))
print("yield")
await asyncio.sleep(0)
print("set event")
flag.set()
print("yield")
await asyncio.sleep(0)
print("wait task")
await t
asyncio.run(main()) asyncio.run(main())

Wyświetl plik

@ -19,3 +19,14 @@ yield
task 3 task 3
task 3 done task 3 done
wait task wait task
----
set event
yield
clear event
yield
yield
task 4
set event
yield
wait task
task 4 done