【问题标题】:Ruby: Threading and socketsRuby:线程和套接字
【发布时间】:2010-07-24 04:34:04
【问题描述】:

我正在尝试用 Ruby 编写一个服务器连接,它会生成一个线程来处理传入连接。然后,该线程将解释传入的数据,然后将一些指令放入队列中,以供主程序循环在其方便时处理。但是,我似乎对队列处理有一些问题,因为程序似乎在某处阻塞,或者主循环只是意外停止工作。这有点难以解释,这里是我的服务器套接字的监听方法:

def listen
  @socket = TCPServer.open(@ip, @port)

  while @looping do
    puts "Waiting for socket accept"
    server = @socket.accept
    puts "Socket accepted"
    serverloop = Thread.new do
      puts "Waiting for response"
      response = server.read
      puts "Command received: #{response}"
      parse_command(response)
      puts "Response complete"
    end 
    processloop = Thread.new do
      while @looping do  
        process_command_queue
        process_response_queue
      end 
    end 
    if interrupted
      exit
    end 
  end 
end

def process_command_queue
  puts "In the command queue"
  if @command_queue.length > 0 
    @command = @queue.pop
    @command.process
  end 
end

建立连接后,输出如下:

magicked$ ./server.rb 
Waiting for socket accept
Socket accepted
Waiting for response
In the command queue
In the command queue ... (repeats)
Waiting for socket accept
In the command queue
In the command queue ... (repeats a lot)
Command received: EXEC 1 1 thisisacommand
Command initialized: EXEC 1 1 thisisacommand
Response complete

在此之后,它再次暂停并等待另一个连接/命令。我期望看到的是“在命令队列中”继续重复。

我可能还没有完全理解红宝石线程的工作方式。我知道 ruby​​ 解释器的实例在执行多个线程时有限制。那么循环是否再次到达@socket.accept 并且它在等待另一个连接时阻塞了其他指令?我的第一个线程是否完成并与主线程重新连接,导致第二个线程做同样的事情?我是否需要 fork 另一个 ruby​​ 解释器来处理其中一个?

最后,有没有人推荐一个很好的资源来帮助解释更高级的 ruby​​ 线程?我发现了很多简单的例子,但显然我还有很多困惑。

感谢您的帮助!

【问题讨论】:

  • 尝试将Thread.abort_on_exception = true 添加到文件顶部。此外,@socket 确实是服务器,server 确实是套接字。 :)
  • 嗯,我不知道eventmachine。 :) 另外,我会尝试 Adrian 的建议。

标签: ruby multithreading


【解决方案1】:

你应该使用eventmachine

【讨论】:

  • evenmachine -> eventmachine?
猜你喜欢
  • 1970-01-01
  • 2019-04-24
  • 2011-02-11
  • 2013-04-02
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-24
相关资源
最近更新 更多