GCD 加信號(hào)量串行進(jìn)行多次網(wǎng)絡(luò)請(qǐng)求操作

printf("處理前創(chuàng)建信號(hào)量,開始循環(huán)異步請(qǐng)求操作\n");

// 1.創(chuàng)建一個(gè)串行隊(duì)列,保證for循環(huán)依次執(zhí)行
        dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);

// 2.異步執(zhí)行任務(wù)
dispatch_async(serialQueue, ^{
    // 3.創(chuàng)建一個(gè)數(shù)目為1的信號(hào)量,用于“卡”for循環(huán),等上次循環(huán)結(jié)束在執(zhí)行下一次的for循環(huán)
    dispatch_semaphore_t sema = dispatch_semaphore_create(1);

    for (int i = 0; i<5; i++) {
        // 開始執(zhí)行for循環(huán),讓信號(hào)量-1,這樣下次操作須等信號(hào)量>=0才會(huì)繼續(xù),否則下次操作將永久停止
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
        printf("信號(hào)量等待中\(zhòng)n");
        // 模擬一個(gè)異步任務(wù)
        NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://github.com"]];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 本次for循環(huán)的異步任務(wù)執(zhí)行完畢,這時(shí)候要發(fā)一個(gè)信號(hào),若不發(fā),下次操作將永遠(yuǎn)不會(huì)觸發(fā)
            [tampArray addObject:@(i)];
            NSLog(@"本次耗時(shí)操作完成,信號(hào)量+1 %@\n",[NSThread currentThread]);
            dispatch_semaphore_signal(sema);

        }];
        [dataTask resume];

    }

    NSLog(@"其他操作");
    for (NSNumber *num in tampArray) {
        NSLog(@"所有操作完成后的操作--->   %@\n",num);
    }

});

雙重信號(hào)量


        //上傳最近的3個(gè)log文件,
        //至少要3個(gè),因?yàn)樽詈笠粋€(gè)是crash的記錄信息,另外2個(gè)是防止其中后一個(gè)文件只寫了幾行代碼而不夠分析
        NSArray *logFilePaths = [fileLogger.logFileManager sortedLogFilePaths];
        
        NSUInteger logCounts = logFilePaths.count;
        
        if (logCounts >= 3) {
            
            dispatch_queue_t queue = dispatch_queue_create(0, DISPATCH_QUEUE_SERIAL);

            dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
            
            dispatch_async(queue, ^{
             
                for (NSUInteger i = 0; i < 3; i++) {
                    
                    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                    
                    NSString *logFilePath = logFilePaths[i];
                    
                    //上傳服務(wù)器
                    
                    NSData *file_total = [NSData dataWithContentsOfFile:logFilePath];
                    
                    KKLogDebug(@"上傳服務(wù)器 logFilePath %@  %@",logFilePath,file_total);
                    
                    if(file_total.length > 0){
                        
                        NSMutableArray *dataArrM = [self uploadLogFileArrWithData:file_total];
                        
                        if(dataArrM.count > 0){

                            dispatch_queue_t queue_upload = dispatch_queue_create(0, DISPATCH_QUEUE_SERIAL);
                            
                            dispatch_semaphore_t semaphore_upload = dispatch_semaphore_create(1);
                            
                            dispatch_async(queue_upload, ^{

                                for(int j = 0; j < dataArrM.count; j++){

                                    dispatch_semaphore_wait(semaphore_upload, DISPATCH_TIME_FOREVER);
            
                                    NSData *data = dataArrM[i];
                                    
                                    KKLogDebug(@"+++++++++ %@ == %zd  %@ totalSize=%@",[NSString stringWithFormat:@"%lu",data.length * j],dataArrM.count,[NSThread currentThread],[NSString stringWithFormat:@"%zd",data.length]);
                                    
                                    [[[KKUtility fetchUploadFileLogWithContent:dataArrM[j] fileName:logFilePath ready:[NSString stringWithFormat:@"%zd",data.length * j+1] totalSize:[NSString stringWithFormat:@"%zd",data.length] status:@"0"] deliverOnMainThread] subscribeNext:^(NSDictionary *result) {
                                        
                                        if (j == dataArrM.count - 1) {
                                            dispatch_semaphore_signal(semaphore);
                                        }
                                        
                                        dispatch_semaphore_signal(semaphore_upload);
                                        
                                        KKLogDebug(@"result  %@",result);
                                        
                                    } error:^(NSError *error) {
                                        
                                        dispatch_semaphore_signal(semaphore);
                                        dispatch_semaphore_signal(semaphore_upload);
                                        KKLogError(@"%@",error);
                                    }];
                                }
                            });
                        }
                    }
                    else {
                        dispatch_semaphore_signal(semaphore);
                    }
                }
              });
              
        }

文件切片:

- (NSMutableArray *)uploadLogFileArrWithData:(NSData *)file_total
{
     NSUInteger allLength = file_total.length;
                          
      NSUInteger subs = 4096;//要切片的大小,

      NSInteger index = 0;//起始位置

      NSMutableArray *dataArray =[NSMutableArray new];
      
      do {

          if (allLength>subs) {
              
              NSRange range =NSMakeRange(index*subs, subs);
              
              index++;
              
//              KKLogDebug(@"%@",NSStringFromRange(range));
              
              [dataArray addObject:[file_total subdataWithRange:range]];
              
              allLength = allLength - subs;

          }else{
              
              NSRange range = NSMakeRange(index*subs, allLength);
              
//              KKLogDebug(@"%@",NSStringFromRange(range));
              
              [dataArray addObject:[file_total subdataWithRange:range]];

              allLength = 0;
          }

          
      } while (allLength>0);
      
//      KKLogDebug(@" dataArray %@",dataArray);//最后得到切片的結(jié)果,數(shù)組里面是NSData對(duì)象
     return dataArray;
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容