I need to protect some code to invalidate a serial queue, in an -invalidate
method, so that these codes would be run once, like the dispatch_once
in the singleton paradigm.
My intuition is:
@property(nonatomic, readonly, getter=isValid) BOOL valid;
@property(nonatomic) dispatch_queue_t serialQueue;
...
- (void)invalidate {
if ([self isValid]){
dispatch_sync(self.serialQueue, ^{
if ([self isValid]) {
_valid = NO;
// relinquish resources here
}
});
if (self.serialQueue) {
dispatch_release (self.serialQueue);
}
}
}
This -invalidate
method would be called either explicitly or by -dealloc
. And I want to make sure that the resources would be relinquished once and only once.
Is this implementation thread-safe?
Is it a better way to implement a dispatch_once
block in a per-instance manner?
@property(nonatomic, readonly) dispatch_once_t invalidated;
...
- (void)invalidate {
dispatch_once(&_invalidated, ^{
dispatch_sync(logQueue, ^{
// double check
if (self.isValid) {
self.valid = NO;
// relinquish things
}
}
}
}