webassembly/asyncio: Implement asyncio.Event class.

Signed-off-by: Damien George <damien@micropython.org>
pull/14193/head
Damien George 2024-04-01 13:44:44 +11:00
rodzic 7ebf3afd3e
commit 21a07eb4fe
3 zmienionych plików z 107 dodań i 1 usunięć

Wyświetl plik

@ -1,7 +1,32 @@
# Minimal asyncio interface that uses JavaScript for scheduling.
# Only implements a very small subset of the asyncio API.
import jsffi
import js, jsffi
class Event:
def __init__(self):
self.clear()
def _set_callbacks(self, resolve, reject):
self._resolve = resolve
self._reject = reject
def is_set(self):
return self._promise is None
def set(self):
if self._promise is not None:
self._resolve()
self._promise = None
def clear(self):
self._promise = js.Promise.new(self._set_callbacks)
async def wait(self):
if self._promise is not None:
await self._promise
return True
class Task:

Wyświetl plik

@ -0,0 +1,57 @@
// Test asyncio.Event.
//
// This test is taken from tests/extmod/asyncio_event.py and adapted:
// - changed asyncio.run(main()) to await main()
// - removed cancel and wait_for parts of the test
const mp = await (await import(process.argv[2])).loadMicroPython();
await mp.runPythonAsync(`
import asyncio
async def task(id, ev):
print("start", id)
print(await ev.wait())
print("end", id)
async def main():
ev = asyncio.Event()
# Set and clear without anything waiting, and test is_set()
print(ev.is_set())
ev.set()
print(ev.is_set())
ev.clear()
print(ev.is_set())
# Create 2 tasks waiting on the event
print("----")
asyncio.create_task(task(1, ev))
asyncio.create_task(task(2, ev))
print("yield")
await asyncio.sleep(0)
print("set event")
ev.set()
print("yield")
await asyncio.sleep(0)
# Create a task waiting on the already-set event
print("----")
asyncio.create_task(task(3, ev))
print("yield")
await asyncio.sleep(0)
# Clear event, start a task, then set event again
print("----")
print("clear event")
ev.clear()
asyncio.create_task(task(4, ev))
await asyncio.sleep(0)
print("set event")
ev.set()
await asyncio.sleep(0)
await main()
`);

Wyświetl plik

@ -0,0 +1,24 @@
False
True
False
----
yield
start 1
start 2
set event
yield
True
end 1
True
end 2
----
yield
start 3
True
end 3
----
clear event
start 4
set event
True
end 4