Skip to content

Instantly share code, notes, and snippets.

@armadsen
Last active December 25, 2015 21: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 armadsen/7045187 to your computer and use it in GitHub Desktop.
Save armadsen/7045187 to your computer and use it in GitHub Desktop.
Demo of separate instances of NSLock in response to this Stack Overflow question: http://stackoverflow.com/q/19451510/344733
#import <Foundation/Foundation.h>
@interface Test : NSObject
- (void)enqueue:(id)object;
- (id)dequeue;
@end
@implementation Test
- (void)enqueue:(id)object
{
NSLog(@"starting enqueue");
NSLock *arrayLock = [[NSLock alloc] init];
[arrayLock lock];
NSLog(@"enqueue locked section");
[arrayLock unlock];
NSLog(@"ending enqueue");
}
- (id)dequeue
{
NSLog(@"starting dequeue");
id result;
NSLock *arrayLock = [[NSLock alloc] init];
[arrayLock lock];
NSLog(@"dequeue locked section");
while (1);
[arrayLock unlock];
NSLog(@"ending dequeue");
return result;
}
@end
int main(int argc, char *argv[]) {
@autoreleasepool {
Test *test = [[Test alloc] init];
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(globalQueue, ^{ [test dequeue]; });
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
dispatch_after(popTime, globalQueue, ^(void){
[test enqueue:@"test"];
});
/* Output:
>> starting dequeue
>> dequeue locked section
>> starting enqueue
>> enqueue locked section
>> ending enqueue
Note that dequeue never returns (Done for the purposes of this example),
so if the two methods were prevented from running simultaneously,
the log statement inside enqueue's locked section would never run,
nor would the 'ending dequeue' log statement
*/
while(1); // Spin to allow stuff on background queue to run.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment