Static variables access from different threads

Discussion in 'Mac Programming' started by satyam90, Jan 19, 2009.

  1. macrumors regular

    satyam90

    Joined:
    Jul 30, 2007
    Location:
    Bangalore, India
    #1
    I am using Cocoa frame work with Obj C programming. I have a class like following:
    Code:
    @interface ClassA: NSObject
    +(int) initCount;
    +(void) initialize;
    +(ClassA*)createNewObject:(int)newValue;
    @end
    
    
    #import "ClassA.h"
    static int count;
    
    @implementation ClassA
    -(id) init {
        self = [super init];
        count++; //some operation on count variable.
        return self;
    }
    
    +(int) initCount {
        return count;
    }
    
    +(void) initialize {
        count = 0;
    }
    
    +(ClassA*)createNewObject:(int)newValue
    {
      count = newValue;
      id ret = [[[self alloc] init] autorelease];
      return ret;
    }
    @end
    

    Now the ClassA's method "createNewObject" is being called from different threads. Now how to protect the static variable "count" being over written/read by threads at a time. I mean, how to prevent the access of "count" by different threads simultaneously.

    I tried to use "NSLock", but throwing exception. Can somebody suggest me how to achieve this?
     
  2. macrumors 68020

    Krevnik

    Joined:
    Sep 8, 2003
    #2
    Have you checked to see what the exception message is? That will usually tell you why it was thrown. It may be just that you are using the lock improperly (which is hard to do, I know).

    Since you are dealing with a simple integer though, you should be able to just use the atomic increment/decrement functions in: <CarbonCore/DriverSynchronization.h>
     

Share This Page