njh / ruby-mqtt

Pure Ruby gem that implements the MQTT protocol, a lightweight protocol for publish/subscribe messaging.
http://www.rubydoc.info/gems/mqtt
MIT License
542 stars 135 forks source link

Use more strict mutex lock for `@socket` #129

Closed cosmo0920 closed 3 years ago

cosmo0920 commented 3 years ago

@socket.write, @socket.close, connected?, and creating @socket are locked with the same mutex. This patch locks them with the same mutex.

Otherwise, IOError may occur on highly traffic and CPU weak environment.

    def send_packet(data)
      # Raise exception if we aren't connected
      raise MQTT::NotConnectedException unless connected? ## connected? is not locked with mutex

      # Only allow one thread to write to socket at a time
      @write_semaphore.synchronize do
        @socket.write(data.to_s) ## connected? is not protected and `@socket.write` causes IOError.
      end
    end

Signed-off-by: Hiroshi Hatake cosmo0920.oucc@gmail.com