Why does this work?

G

Garth Williams

Hi,

thread = Thread.new(thread) do |thisThread|
# thisThread.exit
puts "object id = #{thisThread.object_id}"
end

The code above seems to work, thisThread is the same as thread
(proved by uncommenting out the line), however in most languages this
would not work (I would expect thisThread to be nil), why does it
work in ruby and is it considered good practice?

Also is there a better way to access the current thread?

Thanks.

Garth.
 
D

Dominik Bathon

Hi,

thread =3D Thread.new(thread) do |thisThread|
# thisThread.exit
puts "object id =3D #{thisThread.object_id}"
end

The code above seems to work, thisThread is the same as thread (proved = =20
by uncommenting out the line), however in most languages this would not= =20
work (I would expect thisThread to be nil), why does it work in ruby an= d =20
is it considered good practice?

It doesn't work:

this_thread is nil, so this_tread.exit just calls the private method =20
Kernel#exit with a receiver, this is not allowed, so an exception is =20
thrown and the thread terminates, but you don't see the exception. The =20
following code should make it clear:

thread =3D Thread.new(a =3D thread) do |this_thread|
puts "object id =3D #{this_thread.object_id}"
puts "thread id =3D #{Thread.current.object_id}"
begin
this_thread.exit
rescue Exception =3D> e
p e
end
end
p thread.object_id
p a.object_id
p a

Output:
object id =3D 4
thread id =3D -604525186
#<NoMethodError: private method `exit' called for nil:NilClass>
-604525186
4
nil


Code like

x =3D x + 1

without defining x before this line works, because after the parser saw "=
x =20
=3D", it knows that x is a variable, so "x" later returns nil (which seem=
s =20
to be the default value for an uninitialized variable).

The above code results in:

irb(main):027:0> x =3D x + 1
NoMethodError: undefined method `+' for nil:NilClass
from (irb):27
from :0
Also is there a better way to access the current thread?

Thread.current (see above)

Dominik
 

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

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,142
Latest member
arinsharma
Top