Created
January 3, 2014 02:46
-
-
Save duanhong169/8231709 to your computer and use it in GitHub Desktop.
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 BDSBlockingQueue : NSObject | |
- (void)enqueue:(id)item; | |
- (id)dequeue; | |
@end |
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 "BDSBlockingQueue.h" | |
#define NO_ITEM 0 | |
#define HAS_ITEM 1 | |
@interface BDSBlockingQueue () | |
@property (nonatomic, retain) NSMutableArray *items; | |
@property (nonatomic, retain) NSConditionLock *condLock; | |
@end | |
@implementation BDSBlockingQueue | |
- (id)init | |
{ | |
if (self = [super init]) { | |
self.items = [[NSMutableArray alloc] init]; | |
self.condLock = [[NSConditionLock alloc] initWithCondition:NO_ITEM]; | |
} | |
return self; | |
} | |
- (void)enqueue:(id)item | |
{ | |
[self.condLock lock]; | |
[self.items addObject:item]; | |
[self.condLock unlockWithCondition:HAS_ITEM]; | |
} | |
- (id)dequeue | |
{ | |
id item = nil; | |
[self.condLock lockWhenCondition:HAS_ITEM]; | |
item = [self.items objectAtIndex:0]; | |
[self.items removeObjectAtIndex:0]; | |
NSUInteger count = [self.items count]; | |
[self.condLock unlockWithCondition:(count > 0) ? HAS_ITEM : NO_ITEM]; | |
return item; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment