Thread safty audit & +initialize ?
Thread safty audit & +initialize ?
- Subject: Thread safty audit & +initialize ?
- From: Brant Vasilieff <email@hidden>
- Date: Tue, 24 Jul 2001 23:10:25 -0700
I'm almost done with my threading audit for one application, but I'm
curious. Is it theoretically possible for a class initialization to get
called twice by two threads?
Rather than initializing a static variable within a shared accesser,
I've started using the class method +initialize, which automatically
gets called before the first object of that class is created. I'm
curious if two threads could cause that to happen at the same time,
requiring a lock.
static MyClass* MyClass_sharedObject = nil;
+ (MyClass*)sharedObject
{
if (MyClass_sharedObject == nil)
{
MyClass_sharedObject = [[MyClass alloc] init];
}
return MyClass_sharedObject;
}
Instead I've been coding it like.
static MyClass* MyClass_sharedObject = nil;
+ (void)initialize
{
MyClass_sharedObject = [[MyClass alloc] init];
}
+ (MyClass*)sharedObject
{
return MyClass_sharedObject;
}
It looks like it would be possible, for two threads to cause +initialize
to be called. If not, is it possible for a second thread to interrupt
the +initialize method, and instantiate an object of MyClass?
If so, I guess, I could create a static NSRecursiveLock that was shared
among all +initialize methods for all classes.
Even though nobody answered my earlier question on 'Thread Safty Deja Vu
(retain/autorelease or lock/unlock?)' I found some mistakes, and ended
up having to put locks in accesser and setter methods.
Brant