2016-12-13 56 views
1

是否有可能捕获一个SIGINT来阻止Julia程序运行,但以“有序”方式执行?在JuliaLang处理SIGINT

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信号?

回答

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 

将检查异常是一个interupt,并将与价值,如果这样返回。否则会出错。

+0

这么简单,不知道这是可能的。谢谢 – pkofod