Re: Obj-C runtime not thread-safe?!
Re: Obj-C runtime not thread-safe?!
- Subject: Re: Obj-C runtime not thread-safe?!
- From: Charles Srstka <email@hidden>
- Date: Fri, 18 Jun 2004 04:24:03 -0500
I have written a little sample program that will demonstrate this. Of
course, if you run it normally, the Thing class will initialize almost
instantly and the problem will not occur. But, at least on my G4/450
DP, running this in the debugger slows it down enough to make this
problem occur. Uncomment the first NSLog in Thing.m to see that one of
the threads isn't getting the class object.
main.m:
#import <Foundation/Foundation.h>
#import "ThreadThing.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
ThreadThing *threadThing = [[ThreadThing alloc] init];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
[threadThing doYourThing];
// otherwise the run loop quits immediately
[runLoop addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
[runLoop runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
[threadThing release];
[pool release];
return 0;
}
Thing.h:
#import <Foundation/Foundation.h>
@interface Thing : NSObject {
}
+ (Thing *)thing;
@end
Thing.m:
#import "Thing.h"
@implementation Thing
+ (Thing *)thing {
// you know, I should hope that *this* is thread-safe
return [[[self alloc] init] autorelease];
}
@end
ThreadThing.h:
#import <Foundation/Foundation.h>
@interface ThreadThing : NSObject {
}
- (void)doYourThing;
- (void)doSomethingInNewThread;
@end
ThreadThing.m:
#import "ThreadThing.h"
#import "Thing.h"
@implementation ThreadThing
- (void)doYourThing {
[NSThread detachNewThreadSelector:@selector(doSomethingInNewThread)
toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(doSomethingInNewThread)
toTarget:self withObject:nil];
}
- (void)doSomethingInNewThread {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//NSLog(@"Thing class is %@",[Thing class]);
Thing *thing = [Thing thing];
NSLog(@"thing is %@",thing);
[pool release];
}
@end
Charles
On Jun 18, 2004, at 12:32 AM, j o a r wrote:
Do you know for certain that
"thingWithSomething:somethingElse:andAgain:" is thread safe?
Show the code for that class!
j o a r
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.