The execution time of one operation is unpredictable, and I want to
bound it so that if it's not completed in n seconds it falls back to a
"default" result. This is what I got:

batsman@tux-chan:/tmp$ cat b.rb

require 'thread'

def exec_bounded_time time
        mutex = Mutex.new
        finished = ConditionVariable.new
        completed = "not complete"
        th = Thread.new do
                yield
		# could be killed just here, but don't care
                mutex.synchronize do
                        completed = "completed"
                        finished.signal
                end
        end
        Thread.new do
                sleep time # up to time seconds
                mutex.synchronize do
                        th.kill
                        $stderr.puts "Computation too slow, killing..." if defined? DEBUG
                        finished.signal
                end
        end

        mutex.synchronize { finished.wait mutex  } unless completed == "completed"
	completed
end

DEBUG = true
puts "Status of computation: " + exec_bounded_time(5) { sleep 6 }
puts "Status of computation: " + exec_bounded_time(5) { sleep 1 }


batsman@tux-chan:/tmp$ ruby b.rb
Computation too slow, killing...
Status of computation: not complete
Status of computation: completed

I'm using 2 threads, 1 condition variable and 1 mutex, which seems
too much. I have the feeling that other solutions are possible, and I
kinda thought of using continuations, but I couldn't get the semantics
completely right (I want everything to end when the time limit is
reached OR as soon as the computation is finished).

Improvements?
Where should exec_bounded_time be put in? Another module, top-level...?
Finally, any better name?

-- 
 _           _                             
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ 
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
	Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

Software is like sex; it's better when it's free.
	-- Linus Torvalds