Question

I'm writing a multithreaded application for iPhone, and I'm using NSLock's to make sure that some operations (such as loading sounds from file) will behave as atomic. To simplify acquiring locks from different parts of my application, I wrote following class, that lets me lock and unlock locks just by passing NSString with name. If such lock doesn't exist, it creates it and saves for future. I tested it and it seems to work fine (as it just provides access to NSLock objects and doesn't alter their behavior).

My question is: Is it ok to have and use such class, or do I have some misunderstanding in concept of locks?

Locker.h

#import <Foundation/Foundation.h>

@interface Locker : NSObject { }

+ (void) purgeLocks;
+ (NSLock*) lockWithName: (NSString*) name;
+ (void) lock: (NSString*) name;
+ (void) unlock: (NSString*) name;
+ (BOOL) tryLock: (NSString*) name;

@end



Locker.m

#import "Locker.h"

static NSMutableDictionary* locks = nil;

@implementation Locker

+ (void) initialize {
    locks = [[NSMutableDictionary dictionary] retain];
}

+ (void) purgeLocks {
    [locks release];
    [Locker initialize];
}

+ (NSLock*) lockWithName: (NSString*) name {
    NSLock* lock = nil;
    @synchronized([Locker class]) {
        lock = [locks objectForKey: name];
        if(!lock) {
            lock = [[[NSLock alloc] init] autorelease];
            [lock setName: name];
            [locks setObject: lock forKey: name];
        }
    }
    return lock;
}

+ (void) lock: (NSString*) name {
    [[Locker lockWithName: name] lock];
}

+ (void) unlock: (NSString*) name {
    [[Locker lockWithName: name] unlock];
}

+ (BOOL) tryLock: (NSString*) name {
    return [[Locker lockWithName: name] tryLock];
}

@end

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top