yield

yield()

Switch to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable, and will be restarted immediately if there are no other runnable tasks.

Examples

In the Julia programming language, the function yield()

Switches to the scheduler to allow another scheduled task to run. A task that calls this function is still runnable and will be restarted immediately if there are no other runnable tasks.

julia> @async begin
           println("Task 1")
           yield()
           println("Task 1 resumed")
       end
       @async begin
           println("Task 2")
       end
Task 1
Task 2
Task 1 resumed

In this example, we have two tasks created using the @async macro. The first task prints "Task 1", then calls yield() to switch to the scheduler and allow the second task to run. After the second task completes, the first task is resumed and prints "Task 1 resumed".

Common examples of its use:

  1. Allow other tasks to run in a long-running task:

    @async begin
       println("Task 1")
       # Perform some long-running task
       for i in 1:100000000
           # Do some computation
           if i % 10000000 == 0
               yield()
           end
       end
       println("Task 1 completed")
    end

    In this example, during a long-running task, yield() is called periodically to switch to the scheduler and allow other tasks to run. This helps prevent blocking other tasks and ensures fairness in task execution.

  2. Cooperative multitasking between multiple tasks:
    @async begin
       for i in 1:5
           println("Task 1 - Step $i")
           yield()
       end
       println("Task 1 completed")
    end
    @async begin
       for i in 1:5
           println("Task 2 - Step $i")
           yield()
       end
       println("Task 2 completed")
    end

    This example demonstrates cooperative multitasking between two tasks. Each task performs a set of steps and then yields to allow the other task to run. This way, both tasks progress alternatively.

It's important to note that yield() has limited use outside of asynchronous tasks or when working with Julia's task scheduler. In general, it's not necessary to call yield() explicitly in regular Julia code.

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: