Skip to content

Commit 5e96e89

Browse files
committed
extmod/uasyncio: Add ThreadSafeFlag.
This is a MicroPython-extension that allows for code running in IRQ (hard or soft) or scheduler context to sequence asyncio code. Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
1 parent 4c54012 commit 5e96e89

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

extmod/uasyncio/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"wait_for_ms": "funcs",
1111
"gather": "funcs",
1212
"Event": "event",
13+
"ThreadSafeFlag": "event",
1314
"Lock": "lock",
1415
"open_connection": "stream",
1516
"start_server": "stream",

extmod/uasyncio/event.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ def is_set(self):
1414

1515
def set(self):
1616
# Event becomes set, schedule any tasks waiting on it
17+
# Note: This must not be called from anything except the thread running
18+
# the asyncio loop (i.e. neither hard or soft IRQ, or a different thread).
1719
while self.waiting.peek():
1820
core._task_queue.push_head(self.waiting.pop_head())
1921
self.state = True
@@ -29,3 +31,32 @@ async def wait(self):
2931
core.cur_task.data = self.waiting
3032
yield
3133
return True
34+
35+
36+
# MicroPython-extension: This can be set from outside the asyncio event loop,
37+
# such as other threads, IRQs or scheduler context. Implementation is a stream
38+
# that asyncio will poll until a flag is set.
39+
# Note: Unlike Event, this is self-clearing.
40+
try:
41+
import uio
42+
43+
class ThreadSafeFlag(uio.IOBase):
44+
def __init__(self):
45+
self._flag = 0
46+
47+
def ioctl(self, req, flags):
48+
if req == 3: # MP_STREAM_POLL
49+
return self._flag * flags
50+
return None
51+
52+
def set(self):
53+
self._flag = 1
54+
55+
async def wait(self):
56+
if not self._flag:
57+
yield core._io_queue.queue_read(self)
58+
self._flag = 0
59+
60+
61+
except ImportError:
62+
pass

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy