Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get error messages from ruby threads

I'm having a problem right now where I can't see where my child threads are spitting out error messages which is making it difficult to debug.

eg:

Thread.new{
    a = 1/0
}

Is there any way to have all thread errors print out at stderr?

like image 874
Shalmanese Avatar asked Feb 07 '09 16:02

Shalmanese


People also ask

Is Ruby Array thread-safe?

In standard Ruby implementations, an Array is not thread-safe.

Is multithreading possible in Ruby?

Ruby makes it easy to write multi-threaded programs with the Thread class. Ruby threads are a lightweight and efficient way to achieve concurrency in your code.

Are Ruby hashes thread-safe?

Unfortunately, Ruby doesn't ship with any thread-safe Array or Hash implementations. The core Array and Hash classes are not thread-safe by default, nor should they be.

Is Ruby single threaded or multithreaded?

Multi-threading is the most useful property of Ruby which allows concurrent programming of two or more parts of the program for maximizing the utilization of CPU. Each part of a program is called Thread.


2 Answers

Set the Thread class' abort_on_exception flag to true.

Alternately, wrap the thread body in a throw/catch block and dump the exception in the catch.

like image 158
Morendil Avatar answered Oct 04 '22 20:10

Morendil


Set $DEBUG to true (you can do this from the command line with -d), and you'll get

ruby -d bad_thread.rb 
Exception `LoadError' at /usr/lib/ruby/site_ruby/1.8/rubygems.rb:1113 - no such file to load -- rubygems/defaults/operating_system
Exception `LoadError' at /usr/lib/ruby/site_ruby/1.8/rubygems/config_file.rb:34 - no such file to load -- Win32API
Exception `ZeroDivisionError' at bad_thread.rb:2 - divided by 0
bad_thread.rb:2:in `/': divided by 0 (ZeroDivisionError)
    from bad_thread.rb:2
    from bad_thread.rb:1:in `initialize'
    from bad_thread.rb:1:in `new'
    from bad_thread.rb:1
like image 45
Andrew Grimm Avatar answered Oct 04 '22 19:10

Andrew Grimm