Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fix a potential threadsafe issue
Lazily setting @mutex could lead to have two mutexes with a sample code
like:

    [MyListener.new, MailListener.new].each do |listener|
      Thread.new {
        Wisper::GlobalListeners.add_listener(listener)
      }
    end

This example is cumbersome, but well, it shows the idea. Even with a
singleton, if `add_listener` is called a first time by two different
threads, this could lead to thread safety issues for ruby implementation
without a gvl.

Signed-off-by: chatgris <jboyer@af83.com>
  • Loading branch information
chatgris committed May 14, 2013
1 parent ea21c55 commit 38c7783
Showing 1 changed file with 3 additions and 4 deletions.
7 changes: 3 additions & 4 deletions lib/wisper/global_listeners.rb
Expand Up @@ -3,9 +3,12 @@
module Wisper
class GlobalListeners
include Singleton
attr_reader :mutex
private :mutex

def initialize
@listeners = Set.new
@mutex = Mutex.new
end

def add_listener(listener, options = {})
Expand Down Expand Up @@ -35,10 +38,6 @@ def self.clear

private

def mutex
@mutex ||= Mutex.new
end

def with_mutex
mutex.synchronize { yield }
end
Expand Down

0 comments on commit 38c7783

Please sign in to comment.