gpt4 book ai didi

julia - 如何等待第一个任务完成

转载 作者:行者123 更新时间:2023-12-04 08:28:57 24 4
gpt4 key购买 nike

如果有一组并发任务被调度,如何等待第一个任务完成?

是否存在类似wait([t1, t2], return_when=:FIRST_COMPLETED) 的东西?

function task1()
rt = rand()
@info "task1 time: $rt"
sleep(rt)
@info "task 1 done"
end

function task2()
rt = rand()
@info "task2 time: $rt"
sleep(rt)
@info "task 2 done"
end

t1 = @async task1()
t2 = @async task2()

# wait for just the first completed task
# ???

最佳答案

我认为这样的事情会起作用:

julia> function waitfirst(ts)
c = Channel{Int}()
for (i, t) in enumerate(ts)
@async begin
wait(t)
put!(c, i)
end
end
r = take!(c)
@info "Task $r won"
end
waitfirst (generic function with 1 method)

julia> waitfirst([@async(task1()), @async(task2())])
[ Info: task1 time: 0.6723665203367726
[ Info: task2 time: 0.4815093245244271
[ Info: task 2 done
[ Info: Task 2 won

julia> [ Info: task 1 done
julia>

julia> waitfirst([@async(task1()), @async(task2())])
[ Info: task1 time: 0.3452659680724035
[ Info: task2 time: 0.8576370382519976
[ Info: task 1 done
[ Info: Task 1 won

julia> [ Info: task 2 done
julia>

不过,您必须确保首先安排输入,否则会发生死锁。

关于julia - 如何等待第一个任务完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65121681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com