Skip to content

Commit f8d1257

Browse files
committed
Tutorial: How to poll a ThreadSafeFlag.
1 parent bef5b9b commit f8d1257

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

v3/docs/TUTORIAL.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import uasyncio as asyncio
4242
     3.4.1 [BoundedSemaphore](./TUTORIAL.md#341-boundedsemaphore)
4343
3.5 [Queue](./TUTORIAL.md#35-queue)
4444
3.6 [ThreadSafeFlag](./TUTORIAL.md#36-threadsafeflag) Synchronisation with asynchronous events and interrupts.
45+
     3.6.1 [Querying a ThreadSafeFlag](./TUTORIAL.md#361-querying-a-threadsafeflag) Check its state without blocking.
4546
3.7 [Barrier](./TUTORIAL.md#37-barrier)
4647
3.8 [Delay_ms](./TUTORIAL.md#38-delay_ms-class) Software retriggerable delay.
4748
3.9 [Message](./TUTORIAL.md#39-message)
@@ -1149,6 +1150,48 @@ processing received data.
11491150
See [Threadsafe Event](./THREADING.md#31-threadsafe-event) for a thread safe
11501151
class which allows multiple tasks to wait on it.
11511152

1153+
### 3.6.1 Querying a ThreadSafeFlag
1154+
1155+
The state of a ThreadSafeFlag may be tested as follows:
1156+
```python
1157+
import asyncio
1158+
from select import poll, POLLIN
1159+
from time import ticks_us, ticks_diff
1160+
1161+
async def foo(tsf): # Periodically set the ThreadSafeFlag
1162+
while True:
1163+
await asyncio.sleep(1)
1164+
tsf.set()
1165+
1166+
def ready(tsf, poller):
1167+
poller.register(tsf, POLLIN)
1168+
1169+
def is_rdy():
1170+
return len([t for t in poller.ipoll(0) if t[0] is tsf]) > 0
1171+
1172+
return is_rdy
1173+
1174+
async def test():
1175+
tsf = asyncio.ThreadSafeFlag()
1176+
tsk = asyncio.create_task(foo(tsf))
1177+
mpoll = poll()
1178+
tsf_ready = ready(tsf, mpoll) # Create a ready function
1179+
for _ in range(25): # Run for 5s
1180+
if tsf_ready():
1181+
print("tsf ready")
1182+
t = ticks_us()
1183+
await tsf.wait()
1184+
print(f"got tsf in {ticks_diff(ticks_us(), t)}us")
1185+
else:
1186+
print("Not ready")
1187+
await asyncio.sleep_ms(200)
1188+
1189+
asyncio.run(test())
1190+
```
1191+
The `ready` closure returns a nonblocking function which tests the status of a
1192+
given flag. In the above example `.wait()` is not called until the flag has been
1193+
set, consequently `.wait()` returns rapidly.
1194+
11521195
###### [Contents](./TUTORIAL.md#contents)
11531196

11541197
## 3.7 Barrier

0 commit comments

Comments
 (0)