Skip to content

Weak tasks (auto-cancel when no normal tasks are running) #1189

Open
@Tronic

Description

@Tronic

There are cases where a "monitoring" or "connection pool" task needs to be run within an application's nursery as long as there are other tasks running but it would be more convenient to have them automatically cancelled as soon as their work is no longer required. Such a task can be implemented by making it monitor its parent nursery and self-cancel once no other tasks are running. However, such solution fails if any other task in the same nursery uses similar approach, as they'll see each-other and will never terminate.

I am wondering whether there would be enough use for such feature to justify adding it to Trio core, where it can be reliably detected that only weak tasks are running, also avoiding the need for separate watchdog tasks inside each of the said tasks.

async with trio.open_nursery() as nursery:
    db = Database()
    await nursery.run(db.connection, weak=True)
    nursery.run_soon(important_job, db)
    nursery.run_soon(another_important_job)
    nursery.run_soon(progress_monitor, weak=True)

Whenever a task terminates, Trio would check if only weak tasks are left, and in that case issue nursery.cancel_scope.cancel(), terminating db.connection and progress_monitor (if they are still running).

The same feature could be used for run_race style constructs by marking all tasks weak so that they get auto-cancelled as soon as the nursery body receives the first result and exits.

Maybe there is something fundamentally flawed with this idea, or perhaps there already is a convenient way to handle such cases, without building manual cleanup logic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions