I would like to read an user input without blocking the main thread, much like the getch()
function from conio.h
. Is it possible in Julia?
I tried with @async
but it looked like my input wasn't being read although the main thread wasn't blocked.
The problem, I believe, is either you are running on global scope which makes @async
create its own local variables (when it reads, it reads into a variable in another scope) or you are using an old version of Julia.
The following examples read an integer from STDIN
in a non-blocking fashion.
function foo()
a = 0
@async a = parse(Int64, readline())
println("See, it is not blocking!")
while (a == 0)
print("")
end
println(a)
end
The following two examples do the job in global scope, using an array. You can do the same trick with other types mutable objects. Array example:
function nonblocking_readInt()
arr = [0]
@async arr[1] = parse(Int64, readline())
arr
end
r = nonblocking_readInt() # is an array
println("See, it is not blocking!")
while(r[1] == 0) # sentinel value check
print("")
end
println(r[1])