Open In App

Tasks in Julia

Improve
Improve
Like Article
Like
Save
Share
Report

Tasks are a control flow feature that allows computations to be suspended and resumed in a flexible manner. It is useful for IO-bound tasks, network files etc. The benefits of tasks are less memory and quick processing. It provides a function named task() to create any function as a task. 

The original Task can later be resumed, at which point it will pick up right where it left off.  Julia also supports communication between Tasks through operations like wait and fetch. @task will wrap an expression in a Task without executing it, and return the Task. A task is an iterable object, so the values produced can be used in a loop.

Syntax: task(func)

Parameters:

First create task to execute Function 

Below are some example of Tasks:

Tasks Use
istaskstarted(task)  Tell whether a task has started executing.
 schedule() To add tasks to be automatically scheduled
istaskdone(task) Tell whether a task has exited.
@async It will start a task and return, without waiting for the result of that task being available
current_task() Get the currently running Task.

These are the methods we can use in Julia programming.

Use of istaskstarted() Function

If we want to determine whether a task has started executing. Open the Julia Command-Line and follow the instructions given below:

Step 1: Use for range to find out sum of numbers. Then create the task.

Step 2: Then use istaskstarted() function to check if the task has started. It gives output false means the task has not started executing yet.

Use of schedule() Function

To start the task execution we need to add schedule and yield function. Here, we use schedule() and yield() (switch to the scheduler) to add tasks to be automatically scheduled.

Here, as you can see the task has been started and hence the output results to be true.

Use of istaskdone() Function

If we want to determine whether a task has exited use istaskdone() function. In the following image the output is true which means the task has started to exit.

Use of @async() Method

This method will start a task and return, without waiting for the result of that task being available

Here @time macro executes without waiting for the task, in this case, sleeping for two seconds to complete. The @async wraps an expression in a Task. It means that for whatever falls within its scope, Julia will start this task running.

Check for Current Tasks

To get the currently running tasks, use the function current_task().


Last Updated : 25 Aug, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads