我什至不知道这是否可能,但我想模拟一个真实的生活过程,因为许多人处理许多样本。
假设我有 100 个样本,有 5 个人可以处理这些样本,每个人可以以每小时 20 个的速度处理这些样本。
我有一个处理器类的以下代码,如果它们可以自由地进行处理,它会将样本分配给处理对象。
分配第一个 5 没有问题,但随后我似乎进入了一个无限循环,因为处理器似乎永远不会在计时器过去后将自己设置为“空闲”。关于为什么会发生这种情况或更好的方法的任何建议。目标是能够通过具有不同速率和数量的处理器来对流程进行建模。
-(id)init {
if(![super init])
return nil;
self.free = YES;
self.bookingInRate = 20;
return self;
}
-(void)bookingIn:(NSInteger *)sampleNumber {
self.free = NO;
NSNumber *timeToBookIn = [NSNumber numberWithDouble:((60/self.bookingInRate) * 60)/1000];
NSLog(@"Booking in sample number: %ld", sampleNumber);
NSTimeInterval interval = 1;
NSDate *d = [NSDate dateWithTimeIntervalSinceNow: interval];
NSTimer *t = [[NSTimer alloc] initWithFireDate: d
interval: interval
target: self
selector:@selector(onTick:sampleNumber:)
userInfo:nil repeats:NO];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer:t forMode: NSDefaultRunLoopMode];
}
-(void)onTick:(NSTimer *)timer sampleNumber:(NSInteger *)sampleNumber {
NSLog(@"Booked in sample no: %ld", sampleNumber);
self.free = YES;
}
然后我使用以下方法运行建模循环:
NSMutableArray *sampleNumbers = [[NSMutableArray alloc]init];
for (int i = 1; i <= 10; i++) {
[sampleNumbers addObject:[NSNumber numberWithInteger:i]];
}
NSMutableArray *bookerIns = [[NSMutableArray alloc]init];
for (int i=1; i<=5; i++) {
[bookerIns addObject:[[HEFTBookerIn alloc]init]];
}
int i = 0;
long countSamples;
countSamples = [sampleNumbers count];
// loop sample numbers
while ([sampleNumbers count] != 0 )
{
NSInteger sampleNo = [[sampleNumbers objectAtIndex:i] integerValue];
long count = [bookerIns count];
int counter = 0;
//loop over booker ins
int j;
for (j=0; j <count ; j++) {
HEFTBookerIn *booker = [bookerIns objectAtIndex:counter];
if (booker.free == YES){
dispatch_async(queue, ^{
[booker bookingIn:sampleNo];
});
NSLog(@"Booking in : %ld", sampleNo);
[booker bookingIn:sampleNo];
[sampleNumbers removeObjectAtIndex:i];
//i ++;
break;
} else {
counter ++;
}
}
}