Parallel tasks

2 snippets across 2 stacks - Bash & Linux, Python

SHBash & Linux

Wait for Background Jobs

SH · Process Management
Syntax
wait [pid|%job]
Example
process_a &
process_b &
wait
echo 'Both finished'

Note wait with no arguments paits for all background jobs. With a PID or job spec, it waits for just that one. Useful in scripts to parallelize tasks and then synchronize before continuing.

PYPython

asyncio.TaskGroup (3.11+)

PY · Modern Features
Syntax
async with asyncio.TaskGroup() as tg:
    tg.create_task(coro())
Example
import asyncio

async def fetch(url: str) -> str:
    await asyncio.sleep(0.1)
    return f"Data from {url}"

async def main():
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(fetch("/api/users"))
        task2 = tg.create_task(fetch("/api/orders"))

    print(task1.result())
    print(task2.result())

# asyncio.run(main())
Output
Data from /api/users
Data from /api/orders

Note TaskGroup replaces asyncio.gather() with structured concurrency. If any task raises, all other tasks are cancelled and errors are collected into an ExceptionGroup.

Frequently asked questions

How does Bash & Linux handle parallel tasks?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "Wait for Background Jobs" snippet in Bash & Linux uses `wait [pid|%job]`.
Which command does the Bash & Linux example use?
The "Wait for Background Jobs" snippet uses `wait [pid|%job]`, from the Process Management section of the Bash & Linux cheat sheet.
Which stacks cover "parallel tasks" on this page?
Bash & Linux, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Wait for Background Jobs": wait with no arguments paits for all background jobs. With a PID or job spec, it waits for just that one. Useful in scripts to parallelize tasks and then synchronize before continuing.