在 JuliaLang 中处理 SIGINT

Handling SIGINT in JuliaLang

是否有可能从 运行 捕获 SIGINT 以停止 Julia 程序,但以 "orderly" 方式这样做?

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 秒后结束,因为我没有意识到会花这么长时间,但又不想丢弃所有结果,因为我有另一种方法可以从 [=11 继续=].是否有可能提前(轻轻地)停止它,但使用 SIGINT 信号?

您可以只使用 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

将检查异常是否是中断,如果是,将 return 使用值。否则会报错。