Obj-C runtime not thread-safe?!
Obj-C runtime not thread-safe?!
- Subject: Obj-C runtime not thread-safe?!
- From: Charles Srstka <email@hidden>
- Date: Thu, 17 Jun 2004 23:03:08 -0500
Here's a really weird problem I have. Basically, I'm spawning two
threads at about the same time. Both these threads are running the same
method, but with different arguments. This method starts like this (the
names have been changed to protect the innocent):
- (void)someMethodThatRunsInANewThread:(SomeClass *)someObject
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Thing *justOneOfThoseThings = [Thing thingWithSomething:something
somethingElse:@"somethingElse"
andAgain:yetAnotherObject];
if(justOneOfThoseThings)
{
NSLog(@"got it");
// do lots of neat stuff
}
else
{
NSLog(@"didn't get it");
}
}
"Thing" is a custom class that I have made. The class that this method
is in imports Thing.h. The part I don't get is, if I run the method
that runs the above method in two different threads very soon after the
program launches, a lot of the time only one of the threads gets a
value assigned to justOneOfThoseThings, and the other thread gets NULL.
Every subsequent time that the method is run during that session, it
will work fine in both threads. What's more, if I add some logs to the
thingWithSomething:somethingElse:andAgain: method, those logs never get
called. Confused yet? Here's the catch - if I put this line in between
the autorelease pool and Thing:
NSLog(@"class: %@",[Thing class]);
, then all of a sudden everything works! But, the log displays the
class object in only one of the threads, and NULL in the other one.
After it's tried to get the class once, though, the second time it will
work. So apparently, what is going on is that the Thing class doesn't
get loaded and initialized until the first time it's asked to do
something, so it gets initialized when the first thread tries to call
its class method, and then when the second thread asks for the same
class method almost immediately after, the class isn't initialized yet,
so it fails?
One thing to note is that I've only been able to get this to occur with
ZeroLink-enabled builds. It doesn't occur on normal builds, but is that
because of ZeroLink, or just because a non-ZL build can load the class
faster? Is there still the possibility that this could happen in any
Cocoa app that allocates a new object from a custom class in a thread
if the planets are aligned in a certain way? Do I need to use NSLocks
every time I want to create a new object?! What is going on here?
_______________________________________________
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.