我甚至不知道这是否可能,但我想模拟一个真实的生活过程,因为许多人处理了许多样本。
假设我有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 ++;
}
}
}
答案 0 :(得分:1)
一个突出的问题是你传递了一个在initWithFireDate:interval:target:selector:userInfo:repeats:
的通话中无效的选择器。来自the docs:
aSelector
计时器触发时发送到目标的消息。选择器必须 有以下签名:
- (void)timerFireMethod:(NSTimer*)theTimer
计时器将自身作为此方法的参数传递。
因此,如果它被调用,那么您在此方法中所期望的数据不会被传递回它。尝试使用带调用的计时器而不是目标/操作,或使用dispatch_after()
(我认为后者更直接)。