From: Laurent Sansonetti Date: 2007-07-04T07:26:08+09:00 Subject: Re: Is it possible to detect thread switches? Hi, On 7/3/07, Charlie Savage wrote: > Is there a way to detect a thread context switch? I'm interested, due to > my work on ruby-prof. Currently ruby-prof will report incorrect times > for multi-threaded applications. Take for instance this code: > > def test_thread_timings > RubyProf.start > > sleep(2) > > thread = Thread.new do > sleep(2) > end > > thread.join > > result = RubyProf.stop > end > > ruby-prof will say the inner thread took 2 seconds, but that the outer > thread took 4 (when in fact it was asleep doing nothing for 2 of those > seconds). > > > ruby-prof works by adding an event hook: > > rb_add_event_hook(prof_event_hook, > RUBY_EVENT_CALL | RUBY_EVENT_RETURN | > RUBY_EVENT_C_CALL | RUBY_EVENT_C_RETURN > | RUBY_EVENT_LINE); > > This method gets invoked when a function is entered or left. At that > point ruby-prof knows the current method and thread. But if a thread > switch happens in the middle of the method (assumedly most of the time), > ruby-prof doesn't know it and thus can't stop running the timer on the > first thread. > > Is there anyway to detect this? For RubyCocoa we wrote a patch for the interpreter to be callbacked upon specific threading events, in order to properly save and restore the NSThread contextual data. http://rubycocoa.svn.sourceforge.net/viewvc/*checkout*/rubycocoa/trunk/src/misc/ruby_thread_hooks.diff?revision=1882 (This is still experimental.) If you want to be callbacked upon save and restore thread context, there are also the ruby_sandbox_save and ruby_sandbox_restore function pointers that you can set, if they are available in your version of Ruby. Laurent