[英]Multi-Threading in Ruby
我有一個用ruby制作的TCPserver,該服務器似乎正常工作,可以看到兩個或多個客戶端可以連接並由該服務器提供服務,但是有時它們會卡住(因為需要等待另一個客戶端斷開連接或只是變得不響應),通常在“ pass_ok”位之后,僅與一個客戶端連接時,我看不到此問題。
這是我的代碼:
def self.main_server
begin
server = TCPServer.open(@port)
rescue Exception => e
CoreLogging.syslog_error("Cant start server: #{e}")
end
@main_pid = Process.pid
# Main Loop
Thread.abort_on_exception = true
while true
Thread.fork(server.accept) do |client|
@client = client
sock_domain, remote_port, remote_hostname, remote_ip = @client.peeraddr # Get some info on the incoming connection
CoreLogging.syslog_error("Got new connection from #{@client.peeraddr[3]} Handeled by Thread: #{Thread.current}") # Log incoming connection
@client.puts "Please enter password: " # Password testing (later will be from a config file or DB)
action = @client.gets(4096).chomp # get client password response 'chomp' is super important
if action == @password
# what to do when password is right
pass_ok
Thread.exit
else
# what to do when password is wrong
pass_fail
Thread.exit
end
end
begin
CoreLogging.syslog_error("Thread Ended (SOFT)")
rescue Exception => e
CoreLogging.syslog_error("Thread was killed (HARD)")
end
end
end
我將其留在此處以供將來參考,希望親近的人會發現它有用。
問題是全局@client變量,該變量將覆蓋每個新線程,然后繼承到該線程內的子類。
使用本地客戶端變量(不帶“ @”)可使它按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.