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?

HelloWorld
  • 973
  • 2
  • 9
  • 23
  • 1
    take a look at this question: https://stackoverflow.com/questions/37287020/how-and-when-to-use-async-and-sync-in-julia – Nathan Ripert Sep 25 '18 at 12:07
  • the best way to do this would be with Tasks, or Channels, (or whatever is the 'async-du-jour' that has survived deprecation -- I don't know, I haven't kept up with all the changes to Julia 1.0). I answered a question on Channels some time ago that might be useful to you: https://stackoverflow.com/a/44989053/4183191 – Tasos Papastylianou Sep 25 '18 at 12:20

1 Answers1

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.

Nathan Ripert
  • 872
  • 1
  • 7
  • 18