开发者

Script stops while waiting for user input from STDIN.gets

I'm trying to 开发者_Python百科do something like this, where I have two loops going in seperate threads. The problem I am having is that in the main thread, when I use gets and the script is waiting for user input, the other thread is stopped to wait as well.

class Server
  def initialize
    @server = TCPServer.new(8080)
    run
  end

  def run
    @thread = Thread.new(@server) { |server|
      while true
        newsock = server.accept
        puts "some stuff after accept!"
        next if !newsock
        # some other stuff
      end
    }
  end
end

def processCommand
  # some user commands here
end

test = Server.new
while true do
  processCommand(STDIN.gets)
end

The above is just a sample of what I want to do.

Is there a way to make the main thread block while waiting for user input?


You might want to take a look at using the select method of the IO class. Take a look at

good select example for handling select with asynchronous input. Depending upon what version of ruby you're using you might have issues with STDIN though, I'm pretty sure it always triggers the select in 1.8.6.


I'm not sure if this is what you are looking for, but I was looking for something similar and this example does exactly what I wanted. The thread will continue processing until the user hits enter, and then the thread will be able to handle your user input as desired.

user_input = nil

t1 = Thread.new do
    while !user_input
        puts "Running"
    end
    puts "Stopping per user input: #{user_input}"
end

user_input = STDIN.gets
t1.join
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜