summaryrefslogtreecommitdiffstatshomepage
path: root/tests/extmod/asyncio_threadsafeflag.py
blob: 46da1b7b487a88878027af627bee082dc679329a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# Test Event class

try:
    import asyncio
except ImportError:
    print("SKIP")
    raise SystemExit


import micropython

try:
    micropython.schedule
except AttributeError:
    print("SKIP")
    raise SystemExit


try:
    # Unix port can't select/poll on user-defined types.
    import select

    poller = select.poll()
    poller.register(asyncio.ThreadSafeFlag())
except TypeError:
    print("SKIP")
    raise SystemExit


async def task(id, flag):
    print("task", id)
    await flag.wait()
    print("task", id, "done")


def set_from_schedule(flag):
    print("schedule")
    flag.set()
    print("schedule done")


async def main():
    flag = asyncio.ThreadSafeFlag()

    # Set the flag from within the loop.
    t = asyncio.create_task(task(1, flag))
    print("yield")
    await asyncio.sleep(0)
    print("set event")
    flag.set()
    print("yield")
    await asyncio.sleep(0)
    print("wait task")
    await t

    # Set the flag from scheduler context.
    print("----")
    t = asyncio.create_task(task(2, flag))
    print("yield")
    await asyncio.sleep(0)
    print("set event")
    micropython.schedule(set_from_schedule, flag)
    print("yield")
    await asyncio.sleep(0)
    print("wait task")
    await t

    # Flag already set.
    print("----")
    print("set event")
    flag.set()
    t = asyncio.create_task(task(3, flag))
    print("yield")
    await asyncio.sleep(0)
    print("wait task")
    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())