2

我正在为 iPhone 编写一个多线程应用程序,并且我正在使用 NSLock 来确保某些操作(例如从文件中加载声音)将表现为原子操作。为了简化从我的应用程序的不同部分获取锁,我编写了以下类,它允许我通过传递带有名称的 NSString 来锁定和解锁锁。如果这样的锁不存在,它会创建它并保存以备将来使用。我对其进行了测试,它似乎工作正常(因为它只提供对 NSLock 对象的访问并且不会改变它们的行为)。

我的问题是:拥有和使用这样的类是否可以,还是我对锁的概念有一些误解?

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
4

2 回答 2

1

@synchronized is slow, avoid it. Allocate a lock in + initialize and use that instead. But I'd go for a singleton instead of using class methods, but that's more or less a matter of taste.

The major drawback to your approach is that you have to lock a lock in order to get another lock. In a heavily multihreaded app this meta-lock (your current @synchronized) can become a performance bottleneck even if the threads all want to access different locks.

于 2011-09-15T07:06:48.807 回答
0

This looks quite heavy to me. Are you sure you can’t simplify the design? (GCD comes to mind.) Almost every iOS application is a multithreaded one, and IMHO it’s rare to see such locking helpers as you have written. If there’s a place where the KISS principle shines, I’m sure it’s multithreading.

于 2011-09-15T07:16:19.963 回答