Suppose I have the following function stoptest
where I am able to stop the function from outside the loop by setting a Ref()
object = false. The return variable should equal to the value of the variable in the println
when the function is stopped. e.g.
function stoptest(a, b, rep = Ref(true))
a = Ref(a)
@async for i = 1:b
rep[]||break
println(a[] -= 1)
sleep(5)
end
return(a,rep)
end
This returns
a,cont = stoptest(10,3)
9
(Base.RefValue{Int64}(9), Base.RefValue{Bool}(true))
8
cont[]=false
false
a[]
8
How can I run stoptest
through elements of an Array in a for loop? i.e. The desired output would be
b, cont = trial([10,20,30],3)
9
8
7
(Base.RefValue{Int64}(30), Base.RefValue{Bool}(true))
19
18
17
cont[]=false
false
b[]
17
If I try plugging stoptest
directly into a wrapper function
function trial(J,b, rep = Ref(true))
l = Ref(0)
@async for i = J
rep[] || break
k,rep = stoptest(i,b,rep)
l[]=k[]
end
return (l, rep)
end
The output is
b, cont = trial([10,20,30],3)
9
19
29
(Base.RefValue{Int64}(30), Base.RefValue{Bool}(true))
8
18
28
cont[]=false
false
b[]
30
The function will complete the println
on each element before moving onto the next iteration by dropping the inner @async for loop . However I am still unable to get the function to return the value of k
that is printed in the REPL at the time the function is stopped.
function trial2(J,b, rep = Ref(true))
k = Ref(0)
@async for i = J
k[] = i
for l = 1:b
rep[]||break
println(k[] -= 1)
sleep(5)
end
end
return(k,rep)
end
This is pretty clunky code, but just wondering if there was a simple method to get the desired behavior by plugging stoptest
into a wrapper function or if there was a better way to go about it. Thank you so much!