Julia Community 🟣

programistawpf
programistawpf

Posted on

How to interrupt fun(a,b) in a for loop after 10 seconds?

How to interrupt fun(a,b) in a for loop after 10 seconds?
If terminated before execution, fun x,y,z=false

for i=1:k
x,y,z=fun(a,b)
??? 10 sek > x,y,z=false,false,false
end

Thank you very much for your help, GPT doesn’t know but the matter is urgent!

Top comments (3)

Collapse
 
oheil profile image
oheil • Edited

You can use threads for this. Here is a simple example:

julia> function fun(a,b)
           sleep(a+b)
           return (true,true,true)
       end
fun (generic function with 1 method)

julia> task = Threads.@spawn fun(2,3)
Task (runnable) @0x000001eae0b28200

julia> sleep(10)

julia> if isnothing(task.result)
           x,y,z = (false,false,false)
       else
           x,y,z = fetch(task)
       end
(true, true, true)

julia> task = Threads.@spawn fun(6,6)
Task (runnable) @0x000001eae0b283f0

julia> sleep(10)

julia> if isnothing(task.result)
           x,y,z = (false,false,false)
       else
           x,y,z = fetch(task)
       end
(false, false, false)
Enter fullscreen mode Exit fullscreen mode

It doesn't interrupt the function fun but ignores the result if it takes longer than 10sec and proceeds in the main thread.

Collapse
 
oheil profile image
oheil • Edited

You get faster (and better!) help on discourse:
discourse.julialang.org/

Collapse
 
oheil profile image
oheil • Edited

A link to the discourse discussion:
discourse.julialang.org/t/how-to-i...