Skip to content

Commit 38c7783

Browse files
author
chatgris
committed
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>
1 parent ea21c55 commit 38c7783

1 file changed

Lines changed: 3 additions & 4 deletions

File tree

lib/wisper/global_listeners.rb

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@
33
module Wisper
44
class GlobalListeners
55
include Singleton
6+
attr_reader :mutex
7+
private :mutex
68

79
def initialize
810
@listeners = Set.new
11+
@mutex = Mutex.new
912
end
1013

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

3639
private
3740

38-
def mutex
39-
@mutex ||= Mutex.new
40-
end
41-
4241
def with_mutex
4342
mutex.synchronize { yield }
4443
end

0 commit comments

Comments
 (0)