2

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.

Scath
  • 3,777
  • 10
  • 29
  • 40
  • like `read(STDIN,Char)` ?(https://docs.julialang.org/en/stable/manual/networking-and-streams/#Basic-Stream-I/O-1) – Felipe Lema Apr 09 '18 at 19:04
  • @FelipeLema `read(STDIN, Char)` still needs an "enter" to understand the input. I'm looking for something like `getch()` cause there's a lot of things happening and I can't block the execution waiting the input – Lucas Flores Apr 09 '18 at 19:19

1 Answers1

2

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])
hckr
  • 5,456
  • 1
  • 20
  • 31
  • Note that the `print("")` statement is necessary, or this will be stuck in the `while` loop forever. If anyone more knowledgeable could explain why the print statement is required, that would be greatly appreciated! – MindSeeker Mar 22 '23 at 19:49