我有一个Julia代码,我需要以并行方式执行两个操作。 我的问题是,如果花费太多时间,我需要停止并终止一个操作。
我尝试使用Task
但现在我找不到如何杀死任务。我的代码是:
function mytask(myargs, ch)
# do some work (optimize a problem with Gurobi)
# that can go on for a very long time
put!(ch, computationResult)
end
ch = Channel(1)
task = @async mytask(args, ch)
# now the main task does some other work
# and at the end
if isready(ch)
taskResult = take!(ch)
else
# the result of th async task became useless
# so here I need to kill the async task
end
# continue the execution
我发现了这个类似的老问题,但我认为该解决方案不再受支持,因为我在文档中找不到throwto
方法,我也尝试过,但我收到此错误消息
WARNING: Workqueue inconsistency detected: shift!(Workqueue).state != :queued
ERROR (unhandled task failure): InterruptException:
我不被迫使用任务,我可以使用线程进程或任何其他解决方案,只要它有效
你写道,在等待长计算完成时,你需要在前台进行一些其他处理。@async
仅提供绿色线程机制,因此不适合您的问题 - 您的程序一次只能使用一个Thread
。此外,目前在 Julia 中的任务不支持杀戮机制(除非您自己以某种方式以编程方式执行此操作(。
干净的解决方案是使用JuliaDistributed
机制。下面是一个示例代码片段。
代码开始长时间运行的计算 - 取决于计算是在声明的时间内完成结果或收集,还是进程被终止。
享受!
using Distributed
Distributed.addprocs(1) #we add one worker process that will be the
#long-running background computation
wid = workers()[end] #take last worker (there is just one anyway)
const result = RemoteChannel(()->Channel{Tuple}(1));
@everywhere function longrun(result,c=3,time=0)
#write whatever code you need here
for i in 1:c
sleep(time)
println("Working $i at $(myid())")
end
#we use the RemoteChannel to collect the result
put!(result, (c,time,999999, myid()))
end
function ready_or_not(result,wid)
if !isready(result)
println("Computation at $wid will be terminated")
rmprocs(wid)
return nothing
else
return take!(result)
end
end
remote_do(longrun,wid,result) #this takes far less than a second...
sleep(1)
show(ready_or_not(result,wid)) # .. and you should see the result
remote_do(longrun,wid,result,10,3) #this takes 30s
sleep(7)
show(ready_or_not(result,wid)) #ready_or_not() terminates the worker process
希望有帮助。