超时时终止服务器线程



我从教程中复制了这段代码。每次建立新的TCP连接时,它都会启动一个新线程。

require 'socket'                # Get sockets from stdlib
server = TCPServer.open(2000)   # Socket to listen on port 2000
loop {                          # Servers run forever
  Thread.start(server.accept) do |client|
    client.puts(Time.now.ctime) # Send the time to the client
    client.puts "Closing the connection. Bye!"
    client.close                # Disconnect from the client
  end
}

它工作得很好,但现在我想在超时的情况下终止线程。要做到这一点,我需要终止线程(我不能只是抛出一个异常,因为我必须启用abort_on_exception,这样调试就很容易),但我不知道如何获得线程句柄。

我觉得我应该能够在循环中做这样的事情:

Thread.start(server.accept) do |client, myThread|
    begin
        Timeout::timeout(1) do
            #important stuff
        end
    rescue Timeout::Error
        client.puts "Timeout"
        client.close
        myThread.terminate
    end
end

我也不能用exit替换myThread.terminate,因为这会杀死我的主进程(因为我不完全理解的原因),而且我不希望服务器因为最后一个线程终止而停止运行。

您正在查找Thread.current.terminate

最新更新