Threads terminating

P

pawel

Why this simple program give no output, and terminates immidiatly
after its launched? There should be thread running and giving lots of
'lala', am I right?
class Bar
def initialize

end
def foo
Thread.new do
while true
puts "lala\n"
end
end
end
end

b=Bar.new
b.foo
 
P

Patrick Okui

Why this simple program give no output, and terminates immidiatly
after its launched? There should be thread running and giving lots of
'lala', am I right?
class Bar
def initialize

end
def foo
Thread.new do

try changing this to a = Thread.new
while true
puts "lala\n"
end
end

then add an a.join here
end
end

b=Bar.new
b.foo

Someone else would have to explain why that happens. Don't know enough
about threads (let alone ruby's) to explain that.
 
I

Iñaki Baz Castillo

El Martes, 20 de Octubre de 2009, pawel escribi=F3:
Why this simple program give no output, and terminates immidiatly
after its launched? There should be thread running and giving lots of
'lala', am I right?
class Bar
def initialize
=20
end
def foo
Thread.new do
while true
puts "lala\n"
end
end
end
end
=20
b=3DBar.new
b.foo
=20


When you create a thread, the main threads continues. In you case the main=
=20
thread terminates after calling "Thread.new" so the program exists.

If you want to *wait* all the created threads to finish their work, then yo=
u=20
must "join" them:

my_thread =3D Thread.new do .... end
do other stuff in main thread
my_thread.join



=2D-=20
I=F1aki Baz Castillo <[email protected]>
 
R

Rajinder Yadav

pawel said:
Why this simple program give no output, and terminates immidiatly
after its launched? There should be thread running and giving lots of
'lala', am I right?
class Bar
def initialize

end
def foo
Thread.new do
while true
puts "lala\n"
end
end
end
end

b=Bar.new
b.foo
Hi Pawel, here is one example, see if you can follow it.

class Bar
def initialize( msg )
@msg = msg
end
def foo
t_exit = Time.now.to_i + 3
while true
puts @msg
break if Time.now.to_i > t_exit
sleep 0.5
end
end
end

b1 = Thread.new{ Bar.new("x").foo }
b2 = Thread.new{ Bar.new("o").foo }

# here main thread waits for thread b1 and b2 to exit
b1.join
b2.join


--
Kind Regards,
Rajinder Yadav

http://DevMentor.org
Do Good ~ Share Freely
 
R

Robert Klemme

try changing this to a = Thread.new


then add an a.join here


Someone else would have to explain why that happens. Don't know enough
about threads (let alone ruby's) to explain that.

All threads other than main are demon threads in Ruby, i.e. as has been
explained they do not keep the process alive.

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,781
Messages
2,569,619
Members
45,310
Latest member
FaustoMont

Latest Threads

Top