Re: Threading question
Re: Threading question
- Subject: Re: Threading question
- From: Ken Tozier <email@hidden>
- Date: Sun, 16 May 2004 18:18:41 -0400
On May 16, 2004, at 4:44 PM, Jonathan 'Wolf' Rentzsch wrote:
>
No. Say you have this method:
>
>
- (void) addOne {
>
_total += 1;
>
}
>
>
This method is not thread-safe. Specifically, if two or more threads
>
enter this method at once, you can "lose" an increment. One easy way to
>
make it thread-safe:
>
>
- (void) addOne {
>
@synchronized( self ) {
>
_total += 1;
>
}
>
}
>
What about if none of the methods actually change any values after an
object is created?
For example, would the "containsObject" be non thread safe? Where
methods below would require "synchronized"?
@interface Foo : NSObject
{
NSArray *data;
}
+ (id) newFoo:(NSArray *) inArray;
- (id) initFoo:(NSArray *) inArray;
@end
@implementation Foo
+ (id) newFoo:(NSArray *) inArray
{
return [[[Foo alloc] init] autorelease];
}
- (id) initFoo:(NSArray *) inArray
{
self = [super init];
if (self)
{
data = [inArray retain];
}
return self;
}
- (BOOL) containsObject:(id) inObject
{
NSEnumerator *enumerator = [data objectEnumerator];
id tempObj;
while (tempObj = [enumerator nextObject])
{
if ([tempObj isEqualTo: inObject])
return YES;
}
return NO;
}
Ken
_______________________________________________
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.