Does the argument of Julia function Task(func) have to be a function?

Viewed 44

While trying to learn parallel programming with julia, I came across the function Task(func) which, according to julia documentation, creates a callable task that executes the function func and can be run later. However, it seems that func doesn't have to be a function; any set of statements will do. For example:

t = Task(begin; sleep(5); println("done"); end)
schedule(t)

which gives the following result upon execution with julia 1.6.2

done

This is confusing. Do the set of statements begin; sleep(5); println("done"); end constitute a function (anonymous). If so, how? Thank you for your help.

1 Answers

This is the result of running of the code you have shown:

julia> t = Task(begin; sleep(5); println("done"); end)
done
Task (runnable) @0x000000001ad02400

julia> schedule(t)
Task (failed) @0x000000001ad02400
MethodError: objects of type Nothing are not callable

And this is expected, the code block:

begin; sleep(5); println("done"); end

yields nothing as its value (as this is what println returns), and then nothing is passed as an argument to Task. Then when you try to schedule the task it errors.

Note that the code block:

begin; sleep(5); println("done"); end

gets evaluated before its value is passed to Task constructor.

Related