如何杀死朱莉娅的任务?

时间:2018-08-25 14:01:03

标签: 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

我找到了这个similar old question,但是我认为该解决方案不再受支持,因为我在文档中找不到throwto方法,我也尝试过,但收到了此错误消息

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

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

1 个答案:

答案 0 :(得分:0)

您写道,在等待较长的计算完成时,您需要在前台进行其他处理。 @async仅提供绿色线程机制,因此不适合您的问题-您的程序仍然只能一次使用一个Thread。此外,当前在Julia中的任务不支持查杀机制(除非您自己以编程方式进行查杀)。

干净的解决方案是使用Julia Distributed机制。下面是一个示例代码片段。

代码开始长时间运行的计算-取决于计算是否在声明的时间内完成结果或收集的结果,或进程被终止。

享受!

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

希望有帮助。