tractor/examples/parallelism/single_func.py

48 lines
943 B
Python
Raw Permalink Normal View History

'''
2021-02-27 19:21:27 +00:00
Run with a process monitor from a terminal using::
$TERM -e watch -n 0.1 "pstree -a $$" \
& python examples/parallelism/single_func.py \
&& kill $!
'''
2021-02-27 19:21:27 +00:00
import os
import tractor
import trio
async def burn_cpu() -> int:
'''
Burn CPU briefly and return the current process ID.
2021-02-27 19:21:27 +00:00
'''
pid: int = os.getpid()
2021-02-27 19:21:27 +00:00
# burn a core @ ~ 50kHz
for _ in range(50000):
await trio.sleep(1 / 50000 / 50)
2021-02-27 19:21:27 +00:00
return pid
2021-02-27 19:21:27 +00:00
async def main() -> None:
'''
Run ``burn_cpu()`` in the parent and a subactor.
2021-02-27 19:21:27 +00:00
'''
async with trio.open_nursery() as tn:
2021-02-27 19:21:27 +00:00
# burn rubber in the parent too
tn.start_soon(burn_cpu)
2021-02-27 19:21:27 +00:00
# run the same func as the lone task in a subactor,
# block on and collect its PID as the caller-side result
pid: int = await tractor.to_actor.run(burn_cpu)
2021-02-27 19:21:27 +00:00
print(f'Collected subproc {pid}')
2021-02-27 19:21:27 +00:00
if __name__ == '__main__':
trio.run(main)