discuss-gnustep
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Setter Gettor method style


From: Alexander Malmberg
Subject: Re: Setter Gettor method style
Date: Mon, 05 Aug 2002 13:56:19 +0200

> > > The  rule that  says that  you  must retain  the objects  you need  is
> > > failproof in all cases.
> >
> > No. Obscure cases involving multiple threads could be constructed where
> > [[foo retain] autorelease] worked properly but retaining it after it's
> > been returned doesn't.
> 
> I don't see your point.  If you use multiple threads, unless you have a
> lock, your getter/setter methods are not thread-safe (and so are liable to
> crash at any moment) no matter if you retain foo before or after it is
> returned.  Another thread can always be scheduled in such a perverse way
> as to release foo after you've got its pointer, but before your retain
> method implementation is executed - no matter where you do it, if in the
> caller or in the getter.

True, you don't get it for free, you need to use locks. However,
setters/getters like this would be safe:

-(void) setFoo: (NSString *)newfoo
{
 [foo_lock lock];
 ASSIGN(foo,newfoo);
 [foo_lock unlock];
}

-(NSString *) foo
{
 NSString *retval;
 [foo_lock lock];
 retval=[[foo retain] autorelease];
 [foo_lock unlock];
 return retval;
}

To make a class thread-safe by itself, you have to retain and
autorelease it inside the lock, so you need to do it before returning
it. If you just return the value without doing the retain/autorelease,
you can't get thread safety inside the class; the users would be forced
to handle it themselves.

- Alexander Malmberg



reply via email to

[Prev in Thread] Current Thread [Next in Thread]