curio icon indicating copy to clipboard operation
curio copied to clipboard

ContextTask do not copy parents context

Open vytasrgl opened this issue 2 years ago • 3 comments

Using ContextTask class currently creates empty context for each of the tasks. The desirable behavior would be that child tasks would have access to the parent task context.

Right now it seems its hard to implement the way that would solve it only by modifying the ContextTask code, however it can be solved by running task creation in the parent's context:

        # Create a new task. Putting it on the ready queue
        def new_task(coro):
            # Children should be created with parent context if any
            nonlocal current
            if current and current._context:
                task = current._context.run(taskcls, coro)
            else:
                task = taskcls(coro)
            tasks[task.id] = task
            reschedule_task(task)
            for a in _activations:
                a.created(task)
            return task

vytasrgl avatar Aug 04 '22 09:08 vytasrgl

Just to make sure that I understand this, the primary issue is that new tasks aren't created within the context of the parent task?

All things equal, I don't want the Curio core to be dependent on contextvars. However, it may be possible to restructure things slightly to make this possible. I will investigate.

dabeaz avatar Aug 12 '22 14:08 dabeaz

Yes, indeed, the issue that the new tasks are created outside current context, so those tasks cant access the parent context.

I endup using this patch which does not incluide too much dependancies in the core, but still there are probably better ways to do this. https://github.com/hansonrobotics/curio/commit/1c56eaf7b3b6141ba59be26ab65888782e93f029

vytasrgl avatar Aug 13 '22 03:08 vytasrgl

I made a modification to have the parent task passed to the Task.__init__() method. Let me know if this addresses the problem.

dabeaz avatar Aug 13 '22 13:08 dabeaz