首页 > 解决方案 > async Elixir vs async Julia

问题描述

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?

标签: asynchronouselixirjulia

解决方案


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.


推荐阅读