yieldto

yieldto(task, arg = nothing)

Switch to the given task. The first time a task is switched to, the task's function is called with no arguments. On subsequent switches, arg is returned from the task's last call to yieldto. This is a low-level call that only switches tasks, not considering states or scheduling in any way. Its use is discouraged.

Examples

  1. Switch to a specific task:

    julia> function task_func()
              println("Task running")
              val = yieldto(main_task, "Hello from task_func")
              println("Task resumed with argument: ", val)
          end
    
    julia> task = Task(task_func)
    Task (runnable) @0x0000000120b5d5b0
    
    julia> @async begin
               yield()
               println("Main task resumed")
           end
    Task (runnable) @0x0000000120b5d5b0
    
    julia> yieldto(task)
    Task running
    Main task resumed
    Task resumed with argument: Hello from task_func

    In this example, a new task task is created with task_func as its function. The main task is initially yielded to allow the task to run. The task_func prints a message, yields back to the main task, and then prints the argument received from the last call to yieldto.

  2. Switch to a task with an argument:

    julia> function task_func(arg)
              println("Task running with argument: ", arg)
              yieldto(main_task, "Goodbye from task_func")
          end
    
    julia> task = Task(task_func, "Hello!")
    
    julia> @async begin
               yield()
               println("Main task resumed")
           end
    
    julia> yieldto(task)
    Task running with argument: Hello!
    Main task resumed

    In this example, the task_func takes an argument arg. The task is created with the argument "Hello!". The task prints the argument, yields back to the main task, and the main task resumes execution.

Common mistake example:

julia> yieldto(main_task, "Invalid argument")
ERROR: UndefVarError: main_task not defined

In this example, the main_task variable is not defined, resulting in an UndefVarError. It's important to ensure that the task variable is properly defined before using it in yieldto.

See Also

:@async, :@schedule, :@task, Condition, consume, interrupt, istaskdone, istaskstarted, lock, notify, ReentrantLock, schedule, Task, task_local_storage, unlock, wait, yield, yieldto,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: