【问题标题】:Using Socket and Threads Why Is my Chat Server so Slow and CPU Usage so High?使用套接字和线程 为什么我的聊天服务器这么慢,CPU 使用率这么高?
【发布时间】:2013-04-03 12:23:18
【问题描述】:

所以我的代码工作正常,除了在遍历数组并向多个聊天客户端发送响应时,每个客户端接收响应之间的延迟接近一秒。我在我的计算机上运行服务器和客户端,所以不应该有任何真正的延迟,对吧?我知道红宝石并没有这么慢。另外,为什么我的电脑的风扇在运行时会旋转?如果包含它会有所帮助,还有更多内容。

# Creates a thread per client that listens for any messages and relays them to the server viewer and all the other clients.
create_client_listener_threads = Thread.new do
    x = nil
    client_quantity = 0
    # Loops indefinitely
    until x != nil
        #Checks to see if clients have joined since last check.
        if @client_join_order_array.size > client_quantity
            # Derives number of new arrivals.
            number_of_new_arrivals = @client_join_order_array.size - client_quantity
            # Updates number of clients in client_quantity.
            client_quantity = @client_join_order_array.size
            if number_of_new_arrivals != 0
                # Passes new arrivals into client for their thread creation.
                @client_join_order_array[-1 * number_of_new_arrivals..-1].each do |client|
                    # Creates thread to handle receiving of each client's text.
                    client_thread = Thread.new do
                        loop do
                            text = client.acception.gets
                            # Displays text for server viewer.
                            puts "#{client.handle} @ #{Time.now} said: #{text}"
                            @client_hash.each_value do |value|
                                if value.handle != client.handle
                                    # Displays text for everyone except server viewr and person who spoke.
                                    value.acception.puts "#{client.handle} @ #{Time.now} said: #{text}"
                                end
                            end
                        end
                    end
                end
            end
        end
    end
end

【问题讨论】:

  • 看起来您的循环正在旋转而无需等待。这会使 CPU 变热...
  • 是的。向主线程添加 sleep(1) 解决了我的所有问题。我仍然感到困惑,因为我有其他线程不断旋转,它们不仅仅在每次运行时将一个数字与另一个数字进行比较,但它们不会导致高 CPU 使用率或延迟。
  • 好的。我现在明白了。看起来我的其他线程做得更多,但实际上它们都在等待来自客户端或服务器用户的输入。我认为它们会导致所谓的全局解释器锁定。我假设在等待输入时(至少来自客户)他们必须一遍又一遍地做某事。但这显然不是真的。

标签: multithreading sockets chat latency ruby-1.9.3


【解决方案1】:

不要测试if @client_join_order_array.size > client_quantity,如果它是假的,除了抽CPU 之外什么都不做,你应该接受新的连接,并阻塞直到有一个。换句话说,移动接受连接的代码并将它们添加到此处的数组中。

【讨论】:

  • 感谢您的建议。添加 sleep() 确实阻止了 CPU 冒烟,但是您的想法巩固了我的代码,让我意识到我不需要单独的线程来连接到客户端并添加读取和重新分发其消息的线程。谢谢!
  • 你不需要任何东西,更不用说线程来连接客户端了。客户端连接到您。您所需要的只是一个接受循环,以及每个客户端处理其 I/O 的线程。
猜你喜欢
  • 2022-08-11
  • 1970-01-01
  • 2010-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
  • 1970-01-01
  • 2013-03-20
  • 1970-01-01
相关资源
最近更新 更多