#include "FishThread.h" #include "FishSynchronizedFlag.h" #include "FishSynchronizedValue.h" #define SHOULD_END 1 #define DID_END 2 @implementation FishThread - (void)threadBody:(NSArray*)param { unsigned count = [param count]; SEL sel = count < 1 ? NULL : NSSelectorFromString([param objectAtIndex:0]); id target = count < 2 ? NULL : [param objectAtIndex:1]; id object = count < 3 ? NULL : [param objectAtIndex:2]; NSAutoreleasePool* pool=[[NSAutoreleasePool alloc] init]; NSMutableDictionary* dict=[[NSThread currentThread] threadDictionary]; [dict setObject:[NSValue valueWithNonretainedObject:self] forKey:@"FishThread"]; [pool release]; [target performSelector:sel withObject:object]; pool=[[NSAutoreleasePool alloc] init]; [myThreadStatus bitwiseOperation:eBitwiseOr withValue:DID_END]; [pool release]; } + (FishThread*)currentThread { return [[[[NSThread currentThread] threadDictionary] objectForKey:@"FishThread"] nonretainedObjectValue]; } - initWithSelector:(SEL)selector target:target object:object { [super init]; myThreadStatus=[[FishSynchronizedFlag alloc] init]; NSArray* param=[NSArray arrayWithObjects:NSStringFromSelector(selector), target, object, nil]; [NSThread detachNewThreadSelector:@selector(threadBody:) toTarget:self withObject:param]; return self; } + fishThreadWithSelector:(SEL)selector target:target object:object { return [[[self alloc] initWithSelector:selector target:target object:object] autorelease]; } - (void)setShouldEnd { [myThreadStatus bitwiseOperation:eBitwiseOr withValue:SHOULD_END]; } - (BOOL)shouldEnd { return !!([myThreadStatus flag] & SHOULD_END); } - (void)join { while (! ([myThreadStatus flag] & DID_END)) [NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:.05]]; } - (void)dealloc { [self setShouldEnd]; [self join]; [myThreadStatus release]; [super dealloc]; } @end