Skip to content

Instantly share code, notes, and snippets.

@duanhong169
Created January 3, 2014 02:46
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 duanhong169/8231709 to your computer and use it in GitHub Desktop.
Save duanhong169/8231709 to your computer and use it in GitHub Desktop.
#import <Foundation/Foundation.h>
@interface BDSBlockingQueue : NSObject
- (void)enqueue:(id)item;
- (id)dequeue;
@end
#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