public
Description: RobustThread, threads that won't die when the process does (yay!)
Homepage:
Clone URL: git://github.com/JaredKuolt/robustthread.git
Nicolas Fouché (author)
Fri Aug 21 09:22:36 -0700 2009
commit  9b592837ddd79d37dc4a7b8e92921be10e01bc25
tree    add6faa7ecda2ea2d5379c044840a3103dd2cb7c
parent  eb67c717ae658a375df1dfcbdf5d8c8ca6ec897b
name age message
file LICENSE Tue Jun 02 16:11:42 -0700 2009 Initial commit [JaredKuolt]
file README.rdoc Fri Jun 19 11:54:22 -0700 2009 Add before_exit callback, v0.5.1 [JaredKuolt]
directory lib/ Fri Aug 21 09:22:36 -0700 2009 The main thread can join all threads handled by... [Nicolas Fouché]
file robustthread.gemspec Mon Aug 10 13:28:20 -0700 2009 Catch ALL exceptions for use with exception han... [JaredKuolt]
README.rdoc
Author:Jared Kuolt (me@superjared.com)
Copyright:Copyright © 2009 Jared Kuolt
License:MIT License

RobustThread

This module allows for the creation of a thread that will not simply die when the process dies. Instead, it joins all RobustThreads in Ruby’s exit handler.

Installation

  sudo gem install robustthread

Usage

  rt = RobustThread.new(:args => args, :label => "do_something with x and y") do |x, y|
    do_something(x, y)
  end

Options:

  • args: arguments passed to the thread
  • label: an identifier (used primarily in logs for debugging, defaults to +thread.inspect+)

Easy Looping

You can loop a task in a thread to cleanly exit:

  RobustThread.loop(:seconds => 3) do
    do_something
  end

Options are the same as RobustThread#new, with the addition of seconds, the interval at which the Thread will sleep.

Exception Handling

Since Threads usually eat exceptions, RobustThread allows for a simple global exception handler:

  RobustThread.exception_handler do |exception|
    # Handle your exceptions here
  end

If no handler is assigned, the exception traceback will be piped into the logger as an error message.

Callbacks

RobustThread currently supports 5 callbacks. The following 4 are called per RobustThread.

  RobustThread.add_callback(:before_init){ puts "Before init!" }
  RobustThread.add_callback(:before_yield){ puts "Before yield!" }
  RobustThread.add_callback(:after_yield){ puts "After yield!" }
  RobustThread.add_callback(:after_join){ puts "After join!" }

The before_exit callback is called after all threads are re-joined.

  RobustThread.add_callback(:before_exit){ puts "Before exit!" }

Etc…

If necessary, you can access the actual thread from the RobustThread object via its thread attribute.

  rt.thread
  => #<Thread:0x7fa1ea57ff88 run>

By default, RobustThread uses a Logger that defaults itself to STDOUT. You can change this by assigning the logger class attribute to a different Logger object:

  RobustThread.logger = Logger.new(STDERR)