Project

General

Profile

Actions

Bug #11153

closed

Defining singleton methods using `class << self` sometimes fails when using threads

Added by mattbrictson (Matt Brictson) almost 9 years ago. Updated over 4 years ago.

Status:
Closed
Assignee:
-
Target version:
-
ruby -v:
ruby 2.2.2p95 (2015-04-13 revision 50295) [x86_64-darwin14]
[ruby-core:69182]

Description

Defining singleton methods using this syntax occasionally produces unexpected results when run in parallel with multiple threads:

class << obj
  def method_one
  end
  def method_two
  end
end

Sometimes not all of the methods are defined, leading to this result:

obj.respond_to?(:method_one) # => true
obj.respond_to?(:method_two) # => false

Here is a short script that demonstrates the bug.

require "thread"

def define_singleton_methods_in_thread
  Thread.new do
    100_000.times do
      obj = Object.new
      class << obj
        def one
        end

        def two
        end
        
        def three
        end
      end
      puts "FAIL" unless obj.respond_to?(:three)
    end
  end
end

# Test with 2 threads
2.times.map { define_singleton_methods_in_thread }.map(&:join)

On my machine this script prints "FAIL" 3 times.

I am able to reproduce this bug in 2.0.0-p451, 2.1.6, 2.2.2, and the current ruby_2_2 branch. I cannot reproduce in trunk.

More information here: https://github.com/net-ssh/net-ssh/pull/240

Actions

Also available in: Atom PDF

Like0
Like0Like0