If we just say
def method
Thread.new do
#...
end
end
val = method
Then, obviously, the result is the Thread itself.
If we say
def method
Thread.new do
#...
end.value
end
val = method
The val will equal the result of the final computation in the Thread...but we have to wait for the computation to finish before we get back to execution of the main thread.
Right now, the only thing I'm finding that lets me continue execution normally and get the result of thread's execution is to use the first version (return the thread itself), and then use Thread.value (or, in this case...val.value) when we want to use the actual result of the computation (in which case, if the thread is still executing, the program will yield until it finishes, which is the behavior I think we want).
If anybody has ideas that will get this same sort of behavior without the need to fundamentally change syntax (which is what I'm looking to avoid as much as possible). As awesome as Ruby is, I don't think I can dynamically replace all right-hand side occurrences of specific variables with [variable_name].value...
Just for reference, here's the code I used for testing. If I did something stupid, I'd be glad to hear about it...
puts "testing automatic killing of threads after execution"
t = Thread.new{sleep 1; puts "thread exited"}
puts "Thread sleeping, should see two threads upon inspection"
puts Thread.list.inspect
puts "Let thread join, should only see main thread upon inspection"
t.join
puts Thread.list.inspect
def test_method_1
Thread.new do
sleep 1
1 + 1
end
end
def test_method_2
Thread.new do
sleep 1
1 + 1
end.value
end
puts "start test 2.1"
puts "in this case, t2 will equal the thread, but we will see to threads upon inspection"
t2 = test_method_1
puts Thread.list.inspect
puts t2
puts "start test2.2"
puts "in this case, t2 will equal 2, but the main thread halts during computation"
t2 = test_method_2
puts Thread.list.inspect
puts t2
puts "start test 2.3"
puts "this case sees ideal behavior"
t2 = test_method_1
puts"2 threads!"
puts Thread.list.inspect
puts "desired value! without calling join!...but requires more syntactical care"
puts t2.value
puts "*grumble*"
edit: further grumbling, blogger doesn't like tabs...this is not ideal for posting code. Yes, I know that if I were patient enough to touch html, I could make them display. I'd really rather not waste time formatting these, though...
further edit: what a wondrous age we live in, with our hypertext and our post editing!
1 comment:
Use <pre> </pre> tags to display white space, it should work for tabs. <xmp> works for some browsers, but not all, from what I understand. (Only in HTML 2.0).
(I'm a helpful helping helper!)
Post a Comment