【问题标题】:Handling SIGINT in JuliaLang在 JuliaLang 中处理 SIGINT
【发布时间】:2016-12-13 13:17:30
【问题描述】:

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

【问题讨论】:

    标签: julia signal-handling sigint


    【解决方案1】:

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

    将检查异常是否是中断,如果是,将返回值。否则会出错。

    【讨论】:

    • 这么简单,没想到可以。谢谢
    猜你喜欢
    • 2011-06-16
    • 2016-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多