Reputation: 2577
I have a file that is threading like so:
Thread.new do
# Do something
end.join
My question is about sub threads. I know the above Thread will join with the main thread and the main thread will "wait" for this Thread to complete before it terminates the main thread.
However, how does this life cycle work in something like this example:
Thread.new do
# Do Something
Thread.new do
# Do something else
end.join
end.join
Does the inner thread join to the parent thread or does it join to the main thread? Does the outer thread "wait" on the inner thread and the main thread "wait" on the main thread?
Thanks again!
Upvotes: 1
Views: 681
Reputation: 198466
I know the above Thread will join with the main thread and the main thread will "wait" for this Thread to complete before it terminates the main thread.
It only does it because you said .join
. Ruby doesn't wait for threads; any threads unjoined by the time the program terminates are killed.
Does the inner thread join to the parent thread or does it join to the main thread?
It does exactly what it is told to do: the outer thread says "launch a thread, then join it, then end". The main thread will wait for all that to complete because it, too, was told to .join
the outer thread.
main -launch-----------------------join
outer \---launch-----join---/
inner \---/
Here's an example where the opposite happens - again, only because I explicitly told it to do so:
inner = nil
outer = Thread.new do
inner = Thread.new do
sleep(3)
p "Inner done"
end
sleep(2)
p "Outer done"
end
sleep(1)
inner.join
p "Inner joined"
outer.join
p "Outer joined"
main -launch----------------join---join
outer \---launch-----/------/
inner \---/
Upvotes: 1