• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Thread safty audit & +initialize ?
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

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


  • Follow-Ups:
    • Re: Thread safty audit & +initialize ?
      • From: "John C. Randolph" <email@hidden>
  • Prev by Date: Re: NSOutlineView
  • Next by Date: Re: Obj-C vs Java
  • Previous by thread: Make CocoaDev.com better!
  • Next by thread: Re: Thread safty audit & +initialize ?
  • Index(es):
    • Date
    • Thread