Skip to content

Instantly share code, notes, and snippets.

@hemantborole
Created August 12, 2009 19:46
Show Gist options
  • Save hemantborole/166701 to your computer and use it in GitHub Desktop.
Save hemantborole/166701 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
log = File.open('thread.log','w') ## logging to see threads flow.
TIMEOUT = 3
t1 = Time.now
## Start a timer thread
timer = Thread.start {
log.puts 'Started.. '
while( true )
t2 = Time.now
time_diff = ( t2 - t1 )
if ( time_diff >= TIMEOUT )
log.puts "timer initiating time out..." ## Check for timeout
break ## if timeout, then finish this thread
else
## Log this if you really want to
#log.puts "Time diff is #{time_diff}"
end
end
}
log.puts "Continuing processing.."
log.puts "Sleeping for more than #{TIMEOUT} seconds .. "
## Start the actual processor thread e.g. do the network invocation instead of sleep.
processor = Thread.start {
log.puts 'Starting thread 2'
sleep 4 ## Raise to simulate timeout/Lower to simulate OK condition
}
## Monitor the 2 threads. The one that finishes first is good thread, kill the other.
while( true )
if not processor.alive?
log.puts("processor is dead, so processing is complete, killing thread 1")
timer.kill if timer.alive?
break
else
if timer.alive?
log.puts("timer is alive, continuing processing...")
sleep 1 ## Comment this to poll continously
else
log.puts("timer is dead, timeout has occured, kill processor")
processor.kill if processor.alive?
break
end
end
end
log.puts "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment