首页 > 解决方案 > 如何在 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

我发现了这个类似的旧问题,但我认为不再支持该解决方案,因为我在文档中找不到该throwto方法,我也尝试过,但我收到此错误消息

WARNING: Workqueue inconsistency detected: shift!(Workqueue).state != :queued
ERROR (unhandled task failure): InterruptException:

我不是被迫使用任务,我可以使用线程进程或任何其他解决方案,只要它有效

标签: multithreadingmultiprocessingjulia

解决方案


您写道,在等待长时间计算完成时,您需要在前台进行一些其他处理。@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

希望有帮助。


推荐阅读