Skip to content

Commit

Permalink
fix: make Concurrent::Set thread-safe on CRuby
Browse files Browse the repository at this point in the history
  • Loading branch information
flavorjones committed Apr 20, 2021
1 parent 873ca0c commit 74b3329
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lib/concurrent-ruby/concurrent/set.rb
Expand Up @@ -23,9 +23,13 @@ module Concurrent
# @!macro internal_implementation_note
SetImplementation = case
when Concurrent.on_cruby?
# Because MRI never runs code in parallel, the existing
# non-thread-safe structures should usually work fine.
::Set
require 'monitor'
require 'concurrent/thread_safe/util/data_structures'

class CRubySet < ::Set
end
ThreadSafe::Util.make_synchronized_on_cruby Concurrent::CRubySet
CRubySet

when Concurrent.on_jruby?
require 'jruby/synchronized'
Expand Down
19 changes: 19 additions & 0 deletions lib/concurrent-ruby/concurrent/thread_safe/util/data_structures.rb
Expand Up @@ -12,6 +12,25 @@ def self.synchronized(object, &block)
module Concurrent
module ThreadSafe
module Util
def self.make_synchronized_on_cruby(klass)
klass.class_eval do
def initialize(*args, &block)
@_monitor = Monitor.new
super
end
end

klass.superclass.instance_methods(false).each do |method|
klass.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def #{method}(*args)
monitor = @_monitor
monitor or raise("BUG: Internal monitor was not properly initialized. Please report this to the concurrent-ruby developers.")
monitor.synchronize { super }
end
RUBY
end
end

def self.make_synchronized_on_rbx(klass)
klass.class_eval do
private
Expand Down

0 comments on commit 74b3329

Please sign in to comment.