Skip to content

Instantly share code, notes, and snippets.

@trojanfoe
Last active March 26, 2019 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trojanfoe/7134404 to your computer and use it in GitHub Desktop.
Save trojanfoe/7134404 to your computer and use it in GitHub Desktop.
$ cat locktest.m
#import <Foundation/Foundation.h>
@interface Locker : NSObject {
NSRecursiveLock *_lock;
}
- (void)setLock:(NSRecursiveLock *)lock;
@end
@implementation Locker
- (void)setLock:(NSRecursiveLock *)lock {
if (_lock) {
NSLog(@"%p unlocking %p", self, _lock);
[_lock unlock];
}
_lock = lock;
if (_lock) {
NSLog(@"%p locking %p", self, _lock);
[_lock lock];
}
}
- (void)dealloc {
NSLog(@"%p dealloc", self);
self.lock = nil;
}
@end
@interface TestObject : NSObject {
NSRecursiveLock *_lock;
}
- (void)foo;
- (void)bar;
@end
@implementation TestObject
- (id)init {
self = [super init];
if (self) {
_lock = [[NSRecursiveLock alloc] init];
}
return self;
}
- (void)foo {
Locker *locker = [[Locker alloc] init];
locker.lock = _lock;
NSLog(@"foo in");
[NSThread sleepForTimeInterval:10.0];
NSLog(@"foo out");
}
- (void)bar {
Locker *locker = [[Locker alloc] init];
locker.lock = _lock;
NSLog(@"bar in");
[NSThread sleepForTimeInterval:10.0];
NSLog(@"bar out");
}
@end
int main(int argc, const char **argv) {
@autoreleasepool {
TestObject *testObj = [[TestObject alloc] init];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[testObj foo];
});
[testObj bar];
}
return 0;
}
$ clang -o locktest locktest.m -fobjc-arc -framework Foundation
$ ./locktest
2013-10-24 10:59:21.659 locktest[17027:1603] 0x7fe24ae00050 locking 0x7fe24ac0ad90
2013-10-24 10:59:21.659 locktest[17027:707] 0x7fe24ac0af10 locking 0x7fe24ac0ad90
2013-10-24 10:59:21.660 locktest[17027:1603] foo in
2013-10-24 10:59:31.661 locktest[17027:1603] foo out
2013-10-24 10:59:31.662 locktest[17027:1603] 0x7fe24ae00050 dealloc
2013-10-24 10:59:31.662 locktest[17027:1603] 0x7fe24ae00050 unlocking 0x7fe24ac0ad90
2013-10-24 10:59:31.662 locktest[17027:707] bar in
2013-10-24 10:59:41.664 locktest[17027:707] bar out
2013-10-24 10:59:41.664 locktest[17027:707] 0x7fe24ac0af10 dealloc
2013-10-24 10:59:41.664 locktest[17027:707] 0x7fe24ac0af10 unlocking 0x7fe24ac0ad90
@maddanio
Copy link

i wouldnt count on this. i had instances where the objects are released much later. seems the auto release pools are popped kinda randomly, like in a gc...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment