1/* 2 * Copyright (c) 2006-2008, The RubyCocoa Project. 3 * Copyright (c) 2001-2006, FUJIMOTO Hisakuni. 4 * All Rights Reserved. 5 * 6 * RubyCocoa is free software, covered under either the Ruby's license or the 7 * LGPL. See the COPYRIGHT file for more information. 8 */ 9 10#import <Foundation/NSAutoreleasePool.h> 11#import "RBThreadSwitcher.h" 12#import "osx_ruby.h" 13#import "rubysig.h" 14 15#define DEFAULT_WAIT 0.000 // sec 16#define DEFAULT_INTERVAL 0.005 // sec 17 18static id rthread_switcher = nil; 19 20@implementation RBThreadSwitcher 21 22- init 23{ 24 timer = nil; 25 wait.tv_sec = 0; 26 wait.tv_usec = (int32_t)(DEFAULT_WAIT * 1000 * 1000); 27 return self; 28} 29 30- (NSTimer*) timer 31{ 32 return timer; 33} 34 35- (void) setTimer: (NSTimer*)a_timer 36{ 37 timer = a_timer; 38} 39 40- (void) setWait: (int32_t) usec 41{ 42 wait.tv_usec = usec; 43} 44 45- (void) sched: (NSTimer*)a_timer 46{ 47 CHECK_INTS; 48 if (!rb_thread_critical) rb_thread_schedule(); 49} 50 51- (void) schedWithWait: (NSTimer*)a_timer 52{ 53 CHECK_INTS; 54 if (!rb_thread_critical) rb_thread_wait_for(wait); 55} 56 57+ (void) start: (double)interval wait: (double)a_wait 58{ 59 id pool, a_timer; 60 SEL sel; 61 62 if (rthread_switcher) [self stop]; 63 64 if (a_wait <= 0.0) 65 sel = @selector(sched:); 66 else 67 sel = @selector(schedWithWait:); 68 69 pool = [[NSAutoreleasePool alloc] init]; 70 rthread_switcher = [[self alloc] init]; 71 a_timer = [NSTimer scheduledTimerWithTimeInterval: interval 72 target: rthread_switcher 73 selector: sel 74 userInfo: nil 75 repeats: YES]; 76 [rthread_switcher setTimer: a_timer]; 77 [rthread_switcher setWait: (int32_t)(a_wait * 1000.0 * 1000.0)]; 78 [pool release]; 79} 80 81+ (void) start: (double)interval 82{ 83 [self start: interval wait: DEFAULT_WAIT]; 84} 85 86+ (void) start 87{ 88 [self start: DEFAULT_INTERVAL]; 89} 90 91+ (void) stop 92{ 93 if (rthread_switcher == nil) return; 94 [[rthread_switcher timer] invalidate]; 95 [rthread_switcher release]; 96 rthread_switcher = nil; 97} 98 99@end 100