multithreading - 如何在 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:
我不是被迫使用任务,我可以使用线程进程或任何其他解决方案,只要它有效
解决方案
您写道,在等待长时间计算完成时,您需要在前台进行一些其他处理。@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
希望有帮助。
推荐阅读
- curl - cURL:导入到 mediawiki 时出现 Notoken-Error
- javascript - 登录后重定向到另一个页面而不刷新页面
- android - Android 同步缓存与 CoroutineCache 库
- c++ - 命名空间“Detours”没有成员“uint8_t”
- jquery - 如果选中复选框,我将如何更改气泡颜色?
- node.js - 为具有多个子域的安全、自托管 NextJS 项目提供服务
- python - Python/C++ 包装器在 Pybind11 中使用外部 dll
- arrays - 将 3 字节数组转换为 int32
- javascript - 在函数中添加 CSS
- ruby - Ruby 像 SQL 一样加入 2 个数组