Last active
March 31, 2017 01:37
-
-
Save tetkuz/882057d9f0800608780ccd805b79ee4e to your computer and use it in GitHub Desktop.
Objective-C: AtomicQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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