asynchronous - 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?
解决方案
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.
推荐阅读
- fonts - wxPython - 可以覆盖系统默认字体吗?
- sql - SUM CASE WHEN (SQL)
- xml - 如何在 SPARQL 查询语言中匹配 RDF 三元组中主题的相对 IRI?
- android - Android TransitionManager 下面的视图没有动画
- python - 如何在 docker 上的 Jenkins 中设置 PYTHONPATH
- c++ - C ++无法插入空向量
- scala - 如何避免在Scala的Spark RDD中使用collect?
- python - 如何使用 python webdriver 在此文本框中书写?
- scala - Play Framework 2.5:未定义 trait Filter 类型 => akka.stream.Materializer 中的方法 mat
- paypal - 验证订单 ID 是否存在