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;
}
如果您發現本文對你有所幫助,如果您認為其他人也可能受益,請把它分享出去。