Simple example
Overview¶
This example demonstrates different ways that the same code can be executed. This is an overview of the four cells shown in the animation below.
- Define the coroutine function.
- Cell 'magic'
%callersprints a list of Caller instances and the thread in which it is executing. - Creates an aiologic REvent.
- A button is created and and it runs a loop twice:
- Prints a statement.
- Clears the event.
- Waits for the button click to set the event.
- Cell 'magic'
- Execute
demonormally. - Execute
democoncurrently in a task. - Execute
demoin a thread.
In [1]:
Copied!
import ipywidgets as ipw
from aiologic import REvent
async def demo():
%callers
b = ipw.Button(description="Continue")
event = REvent()
b.on_click(lambda _: event.set())
display(b)
for i in range(1, 3):
event.clear()
b.description = f"Continue {i}"
print(f"Waiting {i}", end="\r")
await event
b.close()
print("\nDone!")
import ipywidgets as ipw
from aiologic import REvent
async def demo():
%callers
b = ipw.Button(description="Continue")
event = REvent()
b.on_click(lambda _: event.set())
display(b)
for i in range(1, 3):
event.clear()
b.description = f"Continue {i}"
print(f"Waiting {i}", end="\r")
await event
b.close()
print("\nDone!")
In [2]:
Copied!
await demo()
await demo()
Name Running Protected Thread
────────────────────────────────────────────────────────
Shell ✓ 🔐 140544958369920 ← current
Control ✓ 🔐 140544817755840
Button(description='Continue', style=ButtonStyle())
Waiting 1
In [3]:
Copied!
# task
await demo()
# task
await demo()
Name Running Protected Thread
────────────────────────────────────────────────────────
Shell ✓ 🔐 140544958369920 ← current
Control ✓ 🔐 140544817755840
Button(description='Continue', style=ButtonStyle())
Waiting 1
In [4]:
Copied!
# thread
await demo()
# thread
await demo()
Name Running Protected Thread
────────────────────────────────────────────────────────────────────
Shell ✓ 🔐 140544958369920
Control ✓ 🔐 140544817755840
async_kernel_caller ✓ 140544382588608 ← current
Button(description='Continue', style=ButtonStyle())
Waiting 1