是否有可能捕获SIGINT以阻止Julia程序运行,但是这样做是有序的"有序的"时尚?
function many_calc(number)
terminated_by_sigint = false
a = rand(number)
where_are_we = 0
for i in eachindex(a)
where_are_we = i
# do something slow...
sleep(1)
a[i] += rand()
end
a, where_are_we, terminated_by_sigint
end
many_calc(100)
说我想在30秒后结束它,因为我没有意识到它需要这么长时间,但不想丢弃所有结果,因为我有另一种方法可以继续{ {1}}。是否可以尽早(轻柔地)停止它,但使用SIGINT信号?
答案 0 :(得分:2)
您可以使用try ... catch ... end
并检查错误是否为中断。
代码:
function many_calc(number)
terminated_by_sigint = false
a = rand(number)
where_are_we = 0
try
for i in eachindex(a)
where_are_we = i
# do something slow...
sleep(1)
a[i] += rand()
end
catch my_exception
isa(my_exception, InterruptException) ? (return a, where_are_we, true) : error()
end
a, where_are_we, terminated_by_sigint
end
将检查异常是否为中断,如果是,则返回值。否则会出错。