Is $! thread safe?

E

Erik Veenstra

From the code below, it appears that $! is thread safe.

Is it?

Thanks.

gegroet,
Erik V. - http://www.erikveen.dds.nl/

----------------------------------------------------------------

# OUTPUT:
# T=1 -> [1, :a, 1]
# T=2 -> [2, :a, 2]
# T=3 -> [3, :b, 2]
# T=4 -> [4, :b, 1]

Thread.abort_on_exception = true

dt = lambda{t0=Time.now ; lambda{|*a| p [(Time.now-t0).to_i,
*a]}}[]

class MyException < StandardError
def initialize(n)
@n = n
end

def inspect
@n.to_s
end
end

(1..2).each do |m|
Thread.new(m) do |n|
begin
sleep(n) # t1 -> sleep(1) ; t2 -> sleep(2)

raise MyException.new(n)
rescue
dt[:a, $!] # t1 -> T=1 ; t2 -> T=2

sleep(5-2*n) # t1 -> sleep(3) ; t2 -> sleep(1)

dt[:b, $!] # t1 -> T=4 ; t2 -> T=3
end
end
end

sleep 5

----------------------------------------------------------------
 
J

Joel VanderWerf

Erik said:

Yes, according to Pickaxe v2, p.319 (the "[thread]" is what signifies this):

Exception Information
$! The exception object passed to raise. [thread]
Exception
$@ Array The stack backtrace generated by the last exception.
See Kernel#caller
on page 497 for details. [thread]
 
J

Joel VanderWerf

Gregory said:
Is that a special case for built in globals? I'm assuming so, but just
curious.

No, only for a subset of them, including $SAFE and the pattern matching
vars.
 
G

Gregory Brown

No, only for a subset of them, including $SAFE and the pattern matching
vars.

Ah, the pattern matching vars were actually the ones I was interested
in... Thanks.
 
E

Erik Veenstra

From the code below, it appears that $! is thread safe.

Yes, according to Pickaxe v2, p.319 (the "[thread]" is what
signifies this):

Exception Information
$! Exception The exception object passed to raise. [thread]

Page 319 of Pickaxe v2 doesn't tell me anything about
exceptions or global variables. But I found the same text on
page 334. (It's not easy to search in a printed book... :})

Page 108 of the same book (at least of _my_ instance) says
"Ruby places a reference to the associated Exception object
into the global variables $!."

I suppose "global" in this sentence means "context of current
thread" instead of "context of current program". It was a bit
confusing to me...

Thanks!

gegroet,
Erik V. - http://www.erikveen.dds.nl/
 
J

Joel VanderWerf

Erik said:
Page 319 of Pickaxe v2 doesn't tell me anything about
exceptions or global variables. But I found the same text on
page 334. (It's not easy to search in a printed book... :})

Sorry about that. I didn't expect that the PDF and the printed copy
would have different pagination...
 

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,755
Messages
2,569,536
Members
45,011
Latest member
AjaUqq1950

Latest Threads

Top