Created
November 1, 2010 11:30
-
-
Save deepak/658022 to your computer and use it in GitHub Desktop.
keep track of the parent of a ruby thread.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
T0 = Thread.main | |
t1 = Thread.new(Thread.current) { |x| Thread.current[:parent] = x; sleep 1_00_000; } | |
t2 = Thread.new(Thread.current) { |x| Thread.current[:parent] = x; sleep 1_00_000; } | |
(t1[:parent] == t2[:parent]) && (t1[:parent] == T0) | |
__END__ | |
# to find out the parent of a thread, ie. was spawned by which thread | |
# we do not do: | |
t1 = Thread.new() { |x| Thread.current[:parent] = Thread.current; sleep 1_00_000; } | |
as inside the block the value of 'Thread.current' can change | |
# GOTCHA: potential memory-leak as we are storing the reference to the thread, the thread will not be reclaimed by GC, if the thread creating is nested. | |
# can use it to keep track of and to restrict nesting, by comparing t1[:parent] == T0 | |
# http://www.tutorialspoint.com/ruby/ruby_multithreading.htm | |
The class method Thread.current returns the Thread object that represents the current thread. This allows threads to manipulate themselves. The class method Thread.main returns the Thread object that represents the main thread.this is the initial thread of execution that began when the Ruby program was started. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment