Skip to content

Instantly share code, notes, and snippets.

@tetkuz
Last active March 31, 2017 01:37
Show Gist options
  • Save tetkuz/882057d9f0800608780ccd805b79ee4e to your computer and use it in GitHub Desktop.
Save tetkuz/882057d9f0800608780ccd805b79ee4e to your computer and use it in GitHub Desktop.
Objective-C: AtomicQueue
#import <Foundation/Foundation.h>
@interface AtomicQueue : NSObject
- (id)init;
- (id)dequeue;
- (void)enqueue:(id)data;
@end
@implementation AtomicQueue {
NSMutableArray *queue;
id lock;
}
- (id)init {
queue = [NSMutableArray new];
return self;
}
- (id)dequeue {
id data = nil;
@synchronized (lock) {
if ([queue count] > 0) {
data = [queue objectAtIndex:0];
[queue removeObjectAtIndex:0];
}
}
return data;
}
- (void)enqueue:(id)data {
@synchronized (lock) {
[queue addObject:data];
}
}
@end
int main() {
AtomicQueue *queue = [AtomicQueue new];
[queue enqueue:(id)5];
[queue :(id)7];
NSInteger j = (NSInteger)[queue dequeue];
NSLog(@"%lu", j);
[queue enqueue:(id)9];
[queue dequeue];
j = (NSInteger)[queue dequeue];
NSLog(@"%lu", j);
j = (NSInteger)[queue dequeue];
NSLog(@"%lu", j);
j = (NSInteger)[queue dequeue];
NSLog(@"%lu", j);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment