mda*_*mda 6 multithreading multiprocessing julia
我有一个 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
Run Code Online (Sandbox Code Playgroud)
我发现了这个类似的老问题,但我认为该解决方案不再受支持,因为我throwto在文档中找不到该方法,我也尝试过,但收到此错误消息
WARNING: Workqueue inconsistency detected: shift!(Workqueue).state != :queued
ERROR (unhandled task failure): InterruptException:
Run Code Online (Sandbox Code Playgroud)
我不是被迫使用任务,我可以使用线程进程或任何其他解决方案,只要它有效
您写道,在等待长时间计算完成时,您需要在前台进行一些其他处理。仅提供绿色线程机制,因此不适合您的问题 - 您的程序仍然一次@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
Run Code Online (Sandbox Code Playgroud)
希望有帮助。
| 归档时间: |
|
| 查看次数: |
2376 次 |
| 最近记录: |