@@ -42,6 +42,7 @@ import uasyncio as asyncio
42
42
  ;  ;  ;  ;  ; 3.4.1 [ BoundedSemaphore] ( ./TUTORIAL.md#341-boundedsemaphore )
43
43
3.5 [ Queue] ( ./TUTORIAL.md#35-queue )
44
44
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.
45
46
3.7 [ Barrier] ( ./TUTORIAL.md#37-barrier )
46
47
3.8 [ Delay_ms] ( ./TUTORIAL.md#38-delay_ms-class ) Software retriggerable delay.
47
48
3.9 [ Message] ( ./TUTORIAL.md#39-message )
@@ -1149,6 +1150,48 @@ processing received data.
1149
1150
See [ Threadsafe Event] ( ./THREADING.md#31-threadsafe-event ) for a thread safe
1150
1151
class which allows multiple tasks to wait on it.
1151
1152
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
+
1152
1195
###### [ Contents] ( ./TUTORIAL.md#contents )
1153
1196
1154
1197
## 3.7 Barrier
0 commit comments