简体   繁体   中英

Ruby threads: methods and instances of objects

Consider the below snippet. In it, I define a single method called doit , which subsequently gets called from two different threads.

Contrary to what I expect, t.object_id in the method keeps returning two distinct IDs, as if the call to the method from each thread received its own space in memory.

What I expected to happen was that on the second thread entering the method, it would replace the Hash previously defined, resulting in the same object ID being printed the rest of the time. In other words, I thought there would have been a single instance of the Hash.

Arguably, this would have suggested that the loop in the first entry of the method would have blocked any subsequent access thereto, but this is obviously not the case.

So what is the deal with methods? Does each invocation from a separate thread receive its own copy in memory? What is the correct way to understand this?

def doit
    t = Hash.new
    puts t.object_id
    loop do
      sleep 1
      puts t.object_id
    end
end

t1 = Thread.new { doit }
t2 = Thread.new { doit }

t1.join
t2.join

By way of example, this is the output:

21329316
21327684
21329316
21327684
21329316
21327684
21327684
21329316
21327684
21329316
21327684
21329316

t is a local variable of doit , it is declared only in the scope of the method. Each execution receives it own t .

If you want to share t , declare it as an instance member @t :

def doit
    @t = Hash.new
    puts @t.object_id
    loop do
      sleep 1
      puts @t.object_id
    end
end

t1 = Thread.new { doit }
t2 = Thread.new { doit }

t1.join
t2.join

Now your output would look like this:

15223760
15223580
15223580
15223580
15223580
15223580
15223580
15223580
15223580
15223580
15223580

Threading has nothing to do with it. t is a local variable initialized on each call to doit —so each call gets its own t . Note that removing the threading gives the same results, albeit not interleaved:

def doit
  t = Hash.new
  t.object_id
end

doit #=> 21329316
doit #=> 21327684

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM