How to access the current topic

When I want to reference the current thread in a thread environment, several strategies seem to work:

  • t = Thread.new{p t}
  • Thread.new{|t| p t}
  • Thread.new{p Thread.current}
  • Thread.new{p self}

Are they all equivalent? Is there a reason for choosing one over the others in a particular context?

+5
source share
3 answers

selfwill work only if you call it directly in the block passed to Thread.new, and not if you call it from a method of another class that runs on this thread. If you use the approach Thread.new { |t| p t}, you will need to go through tif you want to use it in other methods that run in this thread. But it Thread.currentworks no matter where you call it.

Thread.current, , -, . , Thread.new , . self 100% . , Thread.current.

+3

Alex , t = Thread.new{p t} . t , t ( nil) - .

0

: Thread.current -

0

All Articles