If there is two thread calling different methods in objective c, how can avoid that the number will mess up?

74 views Asked by At

For example here is the .m:

-(void)counterPlusOne
{
  [_counter plusOne];
}

-(void)counterMinusOne
{
 [_counter minusOne];
}

There two methods may be called together, or one being called, another will be called as well. For example, if the userCallcountPlusOne, the _counter's plusOne method, may be a lots of thing first. But while the calculating in counterPlusOne, the counterMinusOne may also being called. So, if these two thing go together, the _counter's valuables may be messed up. How can I avoid that? Thanks.

2

There are 2 answers

0
simalone On

Using @synchronized mentioned by @sage444.

You can also use NSRecursiveLock:

@property (retain) NSRecursiveLock *accessLock;

- (id)init{
   self = [super init];
   [self setAccessLock:[[NSRecursiveLock alloc] init]];
   return self;
}

-(void)counterPlusOne
{
   [[self accessLock] lock];
   [_counter plusOne];
   [[self accessLock] unlock];
}

-(void)counterMinusOne{
    [[self accessLock] lock];
    [_counter minusOne];
    [[self accessLock] unlock];
}

And this method used frequently in ASIHTTPRequest source.

0
sage444 On

try use @synchronized if you can't find better solution, because lock in code is bad in definition

-(void)counterPlusOne
{
    @synchronized(_counter)
    {
        [_counter plusOne];
    }
}

-(void)counterMinusOne
{
    @synchronized(_counter)
    {
        [_counter minusOne];
    }
}