3

In Elixir I can run code asynchronously like this

defmodule Async do
   def example do
       process_id = Task.async(fn ->
          #some code you want its result later
       end)
       #do some stuff
       async_result = Task.await(process_id)
    end
end

and, if i don't need any results I can do like this

defmodule Async do
   def example do
       process_id = Task.start_link(fn ->
          #some code you want its result later
       end)
       #do some stuff
       :ok
    end
end

What's the equivalent of above in Julia lang?

2

1 Answer 1

2

if you do not care about the result, you can use @async:

function foo()
    sleep(100)
    sum(1:100)
end

julia> @async foo()
Task (runnable) @0x00007f983b9d5f90

julia>

in the above example you get back the control of the terminal, without having to wait until the end of the execution of foo()

if you want to know the result, and keep an asynchronous behavior, you can use Task, schedule and fetch together:

julia> a() = sum(1:10000)
a (generic function with 1 method)

julia> b = Task(a)
Task (runnable) @0x00007f983b9d5cf0

julia> schedule(b)
Task (done) @0x00007f983b9d5cf0

julia> fetch(b)
50005000

Here is a small piece of code I use to illustrate the different behaviors:

module async

function example1()
    a() = @async sleep(2)
    b = Task(a)
    schedule(b)
    println(fetch(b))
    sleep(4)
    fetch(b)
end

function example2()
    a() = sleep(2)
    b = Task(a)
    schedule(b)
    fetch(b)
end

function example3()
    a() = sum(1:10000)
    b = Task(a)
    schedule(b)
    fetch(b)
end

end;

when I run this code, I get:

julia> async.example1()
Task (runnable) @0x00007f983b9d5510
Task (done) @0x00007f983b9d5510

julia> async.example2()

julia> async.example3()
50005000

async.example2() does not return any result, but keep the terminal busy around 2 seconds since fetch waits for the task to complete before giving back the hand.

2
  • @async returns a Task and can be fetched too, like a = @async (sleep(2); "result"); println(fetch(a))
    – 张实唯
    Sep 26, 2018 at 1:56
  • That is accurate, I did not notice, thanks ! I realise that my async.example1() is a task of a task in fact. Sep 26, 2018 at 8:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.