模拟一次执行100次考试(串行)

1.基本思想:创建串行队列,用信号量控制每一次循环考试。

2.实现 (注意要将for循环需要写在子线程里面,不然可能会卡死主线程)

- (void)testStart{
    self.testNum = 0;
    //法1 dispatch_queue_create  (NULL,默认是串行)
    dispatch_async([HuConfigration sharedHuConfigration].testQueue, ^{
        
        for(int i = 0; i < 80; i++){
            [self testGetExercice];
            dispatch_semaphore_wait([HuConfigration sharedHuConfigration].testsemaphore, DISPATCH_TIME_FOREVER);
        }
        
    });
    
}

- (void)preNext{
    //休眠2s (后台1s内 submitToken会放过去)
    [NSThread sleepForTimeInterval:2.0f];
    self.testNum++;
    dispatch_semaphore_signal([HuConfigration sharedHuConfigration].testsemaphore);
}


- (void)testGetExercice{
    NSDictionary *param;
    param = @{@"releaseStudentId":_reqParamM.releaseStudentId};
    WS(weakSelf);
    [Request requestAppServerNT:param reuestMode:getReqMode funItem:HuFuncItem_getExam success:^(NSDictionary *dic) {
        
        [weakSelf updateAllViewWithData:dic[@"data"]];
        
        //上传答题接口
        [weakSelf testUploadPaper:HuUploadTypeNormal];
        
    } error:^(NSDictionary *dic) {
        [MBProgressHUD showMessage:dic[@"errMsg"]];
        TRACELOG(@"%@",dic[@"errMsg"] ? dic[@"errMsg"] : @"网络异常");
        [weakSelf preNext];
    } failure:^{
        TRACELOG(@"failure");
        [weakSelf preNext];
    }];
}

- (void)testUploadPaper:(HuUploadType)type
{
    NSDictionary *temp;
    NSMutableDictionary *param;
    NSString *funItem;
    
    [self setUploadUserAnsMParams:type];
     _uploadUserAnsM.useTime = 6;
    
    temp = _uploadUserAnsM.mj_keyValues;
    param =@{@"data":[temp nimkit_jsonString]}.mutableCopy;
    funItem = HuFuncItem_uploadExamPaper;
    
    [param setObject:@(_testNum) forKey:@"Time"];
    [param setObject:funItem forKey:@"apiUrl"];
    WS(weakSelf)
    [Request requestAppServerNT:param view:self.view reuestMode:postReqMode funItem:funItem success:^(NSDictionary *dic) {
        wyLog(@"Time=%d,back_upload_success",weakSelf.testNum);
        [weakSelf preNext];
    } error:^(NSDictionary *dic) {
        NSMutableDictionary *muDict = [NSMutableDictionary dictionaryWithDictionary:dic];//拼接参数
        [muDict addEntriesFromDictionary:param];
        wyLog(@"Time=%d,back_upload_error=%@",weakSelf.testNum,muDict);
        [weakSelf preNext];
    } failure:^{
        wyLog(@"Time=%d,back_upload_failure",weakSelf.testNum);
        [weakSelf preNext];
    }];
    
}

@implementation HuConfigration

- (dispatch_semaphore_t)testsemaphore{
    if (_testsemaphore == nil) {
        _testsemaphore = dispatch_semaphore_create(0);
    }
    return _testsemaphore;
}

- (dispatch_queue_t)testQueue
{
    if(_testQueue == nil){
        _testQueue = dispatch_queue_create("com.317hu.gcd.testQueue", DISPATCH_QUEUE_CONCURRENT);
    }
    return _testQueue;
}

如果您发现本文对你有所帮助,如果您认为其他人也可能受益,请把它分享出去。

你可能感兴趣的:(模拟一次执行100次考试(串行))