Skip to content

Instantly share code, notes, and snippets.

@mindbrix
Created February 28, 2014 20:18
Show Gist options
  • Save mindbrix/9279012 to your computer and use it in GitHub Desktop.
Save mindbrix/9279012 to your computer and use it in GitHub Desktop.
//
// NTBFifoOperationQueue.h
// Timeline
//
// Created by Nigel Barber on 19/11/2013.
// Copyright (c) 2013 Nigel Barber. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NTBFifoOperationQueue : NSOperationQueue
@end
//
// NTBFifoOperationQueue.m
// Timeline
//
// Created by Nigel Barber on 19/11/2013.
// Copyright (c) 2013 Nigel Barber. All rights reserved.
//
#import "NTBFifoOperationQueue.h"
@interface NTBFifoOperationQueue ()
@property( nonatomic, retain ) NSMutableArray *fifo;
@end
@implementation NTBFifoOperationQueue
-(id)init
{
self = [ super init ];
if( self )
{
self.fifo = [ NSMutableArray new ];
}
return self;
}
-(void)addOperation:(NSOperation *)operation
{
NSMutableArray *fifo = self.fifo;
void (^moveToQueue)(void) = ^void(void)
{
@synchronized( self )
{
if( fifo.count )
{
NSOperation *operationToQueue = fifo[ 0 ];
[ super addOperation:operationToQueue ];
[ fifo removeObjectAtIndex:0 ];
}
}
};
if( self.operationCount < self.maxConcurrentOperationCount )
{
[ super addOperation:operation ];
}
else
{
[ self.operations enumerateObjectsUsingBlock:^( NSOperation *operationToCancel, NSUInteger idx, BOOL *stop )
{
if( ! operationToCancel.isCancelled )
{
[ operationToCancel setCompletionBlock:moveToQueue ];
[ operationToCancel cancel ];
*stop = YES;
}
}];
@synchronized( self )
{
if( fifo.count >= self.maxConcurrentOperationCount )
{
[ fifo removeObjectAtIndex:0 ];
}
[ fifo addObject:operation ];
}
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment