bile cevap zarif ve farklı çözüm yoktur, doğrudur:, iplik güvensiz nesneleri kullanarak bu konuda nedeniyle değişkenin istenmeyen salımının olası hatayı önlemek olabilir zaman
- (id)init {
self = [super init];
if (self != nil) {
NSString *label = [NSString stringWithFormat:@"%@.isolation.%p", [self class], self];
self.isolationQueue = dispatch_queue_create([label UTF8String], NULL);
label = [NSString stringWithFormat:@"%@.work.%p", [self class], self];
self.workQueue = dispatch_queue_create([label UTF8String], NULL);
}
return self;
}
//Setter, write into NSMutableDictionary
- (void)setCount:(NSUInteger)count forKey:(NSString *)key {
key = [key copy];
dispatch_async(self.isolationQueue, ^(){
if (count == 0) {
[self.counts removeObjectForKey:key];
} else {
self.counts[key] = @(count);
}
});
}
//Getter, read from NSMutableDictionary
- (NSUInteger)countForKey:(NSString *)key {
__block NSUInteger count;
dispatch_sync(self.isolationQueue, ^(){
NSNumber *n = self.counts[key];
count = [n unsignedIntegerValue];
});
return count;
}
kopya önemlidir . İş parçacığı güvenli varlıklara gerek yok.
daha kuyruk özel kuyruğu beyan NSMutableDictionary kullanması ve ayarlayıcı değiştirmek isterseniz:
self.isolationQueue = dispatch_queue_create([label UTF8String], DISPATCH_QUEUE_CONCURRENT);
- (void)setCount:(NSUInteger)count forKey:(NSString *)key {
key = [key copy];
dispatch_barrier_async(self.isolationQueue, ^(){
if (count == 0) {
[self.counts removeObjectForKey:key];
} else {
self.counts[key] = @(count);
}
});
}
ÖNEMLİ!
Sen dispatch_barrier_sync
Detaylı açıklama bu marvelous blog article olduğunu sadece basit dispatch_sync olduğunu onsuz bir kendi özel kuyruk ayarlamak zorunda.
Çoklu iş parçacığı konusunda uzman değilim, ancak "atomik" işaretlemenin (sentezlemeli erişimciler için varsayılan) iş parçacığı güvenliği konusunda hiçbir garanti vermediğini biliyorum. Yine de, bunu ilk kez okurken aynı şeyi düşündüm. –