ios解決多執行緒忘記釋放lock的
為了解決多執行緒忘記釋放lock的問題,引入哨兵ThreadGuard
#import<Foundation/Foundation.h>
@interface ThreadGuard :NSObject
- (instancetype)initWithLock:(NSLock *)lock;
- (void)unlock;
@end
#import "ThreadGuard.h"
@interfaceThreadGuard ()
@property (nonatomic,strong) NSLock *lock;
@end
@implementation ThreadGuard
- (void)dealloc
{
[_lockunlock];
_lock =nil;
}
- (instancetype)initWithLock:(NSLock *)lock
{
self = [superinit];
if (self) {
_lock = lock;
[_locklock];
}
returnself;
}
- (void)unlock
{
[_lockunlock];
}
@end
#import "ThreadGuard.h"
@interfaceViewController ()
@property (nonatomic,strong) NSLock *lock;
@end
@implementation
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
for (NSInteger index =0; index < 1000; index++) {
[selftest];
}
}
- (void)test
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
ThreadGuard *guard = [[ThreadGuardalloc] initWithLock:self.lock];
NSLog(@"-----1111------");
BOOL result =YES;
if (result) {
return;
}
NSLog(@"-----222------");
guard = nil;
});
}
- (NSLock *)lock
{
if (nil ==_lock) {
_lock = [[NSLockalloc] init];
}
return_lock;
}
@end