iOS 開發之多線程之GCD

來源:互聯網
上載者:User

標籤:gcd   ios   線程   多線程   並發   

1.GCD(Grand Centrol Dispath)

並行:宏觀以及微觀都是兩個人再拿著兩把鐵鍬在挖坑,一小時挖兩個大坑

並發:宏觀上是感覺他們都在挖坑,微觀是他們是在使用一把鐵鍬挖坑,一小時後他們挖了兩個小坑。

總結:就單個cpu來說,大部分進程是並發進行的,就是一把鐵鍬,你一下我一下,只是間隔時間較短,使用者感覺不到而已。


應用:

GCD包括:

(1)實際使用中

//dispatch_get_global_queue(0, 0)第一個0是優先順序,第二個保留欄位
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //在這裡可以是資料請求
         NSString* result = [self requestData:parameter];
        //在這裡返回主線程重新整理資料
        dispatch_async(dispatch_get_main_queue(), ^{
            [mainTableView reloadData];
        });
    });

舉例說明:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSURL * url = [NSURL URLWithString:@"http://www.baidu.com"];
    NSError * error;
    NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    if (data != nil) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"call back, the data is: %@", data);
        });
    } else {
        NSLog(@"error when download:%@", error);
    }
});


(2)也可以自己建立(我是不怎麼用)

串列隊列,顧名思義,一串嘛,那就得並發執行嘍

//自己建立serial queue
    dispatch_queue_t queue = dispatch_queue_create("com.class15.queue", DISPATCH_QUEUE_SERIAL);
    //非同步執行線程
    dispatch_async(queue, ^{
        NSLog(@"任務1:%@  %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
    });



並行隊列通過dispatch_get_global_queue擷取,由系統建立三個不同優先順序的dispatch queue

//建立自己的隊列
    dispatch_queue_t queue = dispatch_queue_create("com.class15.comcrrentQueue", DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_async(queue, ^{
        NSLog(@"任務1:%@  %d", [NSThread currentThread],[NSThread currentThread].isMainThread);
    });

iOS 開發之多線程之GCD

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.