Task

Task(func)

Create a Task (i.e. thread, or coroutine) to execute the given function (which must be callable with no arguments). The task exits when this function returns.

Examples

  1. Create a basic task:

    julia> task1 = Task(() -> println("Executing task 1"))
    Task (runnable) @0x00007f8a8a8a8a8a
    
    julia> schedule(task1)

    This example creates a Task that executes a function that prints a message. The schedule function is used to schedule and start the task.

  2. Create a task with a custom function:

    julia> function myfunction()
              println("Executing custom function")
          end
    
    julia> task2 = Task(myfunction)
    Task (runnable) @0x00007f8a8b8b8b8b
    
    julia> schedule(task2)

    In this example, a custom function myfunction is defined and a task task2 is created using that function. The schedule function is then used to start the task.

  3. Handle task completion:

    julia> function task_completed(task)
              println("Task completed")
          end
    
    julia> task3 = Task(() -> println("Executing task 3"))
    Task (runnable) @0x00007f8a8c8c8c8c
    
    julia> oncompletion(task3, task_completed)
    
    julia> schedule(task3)

    This example demonstrates how to handle task completion using the oncompletion function. The task_completed function is executed when task3 completes.

Common mistake example:

julia> mytask = Task(42)
ERROR: MethodError: no method matching Task(::Int64)

In this example, a mistake is made by passing an integer (42) instead of a callable function to the Task constructor. The argument to Task should be a function that can be called with no arguments.

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: