GCD實例

轉自http://blog.csdn.net/jjunjoe/article/details/8743434,學習了,感謝


示例源碼清單如下:

1SingletonSample.h

//

//  SingletonSample.h

//  BlockSample

//

//  Created by developer on 13-9-27.

//  Copyright (c) 2013 developer. All rights reserved.

//


#import <Foundation/Foundation.h>


@interface SingletonSample : NSObject


+ (id)ShareInstance;

@end



2SingletonSample.m

//

//  SingletonSample.m

//  BlockSample

//

//  Created by developer on 13-9-27.

//  Copyright (c) 2013 developer. All rights reserved.

//


#import "SingletonSample.h"


@implementation SingletonSample

+ (id)ShareInstance{

    static SingletonSample *SharedInstance = nil;

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        SharedInstance = [[SingletonSample alloc] init];

    });

    

    return SharedInstance;

}

@end


3BlockSampleTests.h

//

//  BlockSampleTests.h

//  BlockSampleTests

//

//  Created by developer on 13-8-3.

//  Copyright (c) 2013 developer. All rights reserved.

//


#import <SenTestingKit/SenTestingKit.h>


@interface BlockSampleTests : SenTestCase


@end


4BlockSampleTests.m

//

//  BlockSampleTests.m

//  BlockSampleTests

//

//  Created by developer on 13-8-3.

//  Copyright (c) 2013 developer. All rights reserved.

//


#import "SingletonSample.h"

#import "BlockSampleTests.h"


static int global = 100;


static volatile BOOL flag = NO;


static const int Length = 100;

static int data[Length];

static void initData()

{

    for(int i = 0; i < Length; i++)

        data[i] = i + 1;

}



@implementation BlockSampleTests


- (void)setUp

{

    [super setUp];

    

    // Set-up code here.

}


- (void)tearDown

{

    // Tear-down code here.

    

    [super tearDown];

}


- (void)test1

{

    // 默認打印一條語句"Hello, World!"

    NSLog(@"Hello, World!");

}


- (void)testBlock1

{

    // block 打印一條語句"Hello, World!"

    void (^aBlock)(void) = ^(void){ NSLog(@"Hello, World!"); };

    aBlock();

}


- (void)testBlock2

{

    // block 打印一條語句"Hello, World!"

    void (^aBlock)(void) = 0;

    aBlock = ^(void) {

        NSLog(@"Hello, World!");

    };

    

    aBlock();

}


- (void)testBlockArray

{

    // block 數組

    void (^blocks[2])(void) = {

        ^(void){ NSLog(@" >> This is block 1!"); },

        ^(void){ NSLog(@" >> This is block 2!"); }

    };

    

    blocks[0]();

    blocks[1]();

}


- (void)testBlock4

{

    /*

     block 是分配在 stack 上的,這意味着我們必須小心裏處理 block 的生命週期。

     比如如下的做法是不對的,因爲 stack 分配的 block  if  else 內是有效的,但是到大括號 } 退出時就可能無效了:

     */

    

    dispatch_block_t block;

    BOOL x = 1;

    

    if (x) {

        block = ^{ printf("true\n"); };

    } else {

        block = ^{ printf("false\n"); };

    }

    block();

}


- (void)testBlock5

{

    /*

     考慮到 block 的目的是爲了支持並行編程,對於普通的 local 變量,我們就不能在 block 裏面隨意修改(原因很簡單,block 可以被多個線程並行運行,會有問題的)

     而且如果你在 block 中修改普通的 local 變量,編譯器也會報錯。

     那麼該如何修改外部變量呢?有兩種辦法:

     第一種是可以修改 static 全局變量;

     第二種是可以修改用新關鍵字 __block 修飾的變量。

     */

    __block int blockLocal  = 100;

    static int staticLocal  = 100;

    

    void (^aBlock)(void) = ^(void){

        NSLog(@" >> Sum: %d\n", global + staticLocal);

        

        global++;

        blockLocal++;

        staticLocal++;

    };

    

    aBlock();

    

    NSLog(@"After modified, global: %d, block local: %d, static local: %d\n", global, blockLocal, staticLocal);

    

}


- (void)testBlock6

{

    /*

     我們也可以引用 static block  __block block。比如我們可以用他們來實現 block 遞歸

     */

    

    void (^aBlock)(int) = 0;

    static void (^ const staticBlock)(int) = ^(int i) {

        if (i > 0) {

            NSLog(@" >> static %d", i);

            staticBlock(i - 1);

        }

    };

    

    aBlock = staticBlock;

    aBlock(5);

    

    // 2

    __block void (^blockBlock)(int);

    blockBlock = ^(int i) {

        if (i > 0) {

            NSLog(@" >> block %d", i);

            blockBlock(i - 1);

        }

    };

    

    blockBlock(5);

}


- (void)testBlock7

{

    /*

     上面我們介紹了 block 及其基本用法,但還沒有涉及並行編程。

     block  Dispatch Queue 分發隊列結合起來使用,是 iOS 中並行編程的利器。

     */

    

    // create dispatch queue

    dispatch_queue_t queue = dispatch_queue_create("StudyBlocks",NULL);

    

    dispatch_async(queue, ^(void) {

        int sum = 0;

        for(int i = 0; i < Length; i++)

            sum += data[i];

        

        NSLog(@" >> Sum: %d", sum);

        

        flag = YES;

    });

    

    // wait util work is done.

    while (!flag);

    dispatch_release(queue);

    

}


- (void)testBlock8

{

    /*

     在上面的例子中,我們的主線程一直在輪詢 flag 以便知曉 block 線程是否執行完畢,這樣做的效率是很低的,嚴重浪費 CPU 資源。

     我們可以使用一些通信機制來解決這個問題,如:semaphore(信號量)。

     semaphore 的原理很簡單,就是生產-消費模式,必須生產一些資源才能消費,沒有資源的時候,那我就啥也不幹,直到資源就緒。

     */

    

    initData();

    

    // Create a semaphore with 0 resource

    __block dispatch_semaphore_t sem = dispatch_semaphore_create(0);

    

    // create dispatch semaphore

    dispatch_queue_t queue = dispatch_queue_create("StudyBlocks",NULL);

    

    dispatch_async(queue, ^(void) {

        int sum = 0;

        for(int i = 0; i < Length; i++)

            sum += data[i];

        

        NSLog(@" >> Sum: %d", sum);

        

        // signal the semaphore: add 1 resource

        dispatch_semaphore_signal(sem);

    });

    

    // wait for the semaphore: wait until resource is ready.

    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

    

    dispatch_release(sem);

    dispatch_release(queue);

}


- (void)testBlock9

{

    /*

     下面我們來看一個按照 FIFO 順序執行並用 semaphore 同步的例子:先將數組求和再依次減去數組。

     */

    initData();

    

    __block int sum = 0;

    

    // Create a semaphore with 0 resource

    __block dispatch_semaphore_t sem = dispatch_semaphore_create(0);

    __block dispatch_semaphore_t taskSem = dispatch_semaphore_create(0);

    

    // create dispatch semaphore

    dispatch_queue_t queue = dispatch_queue_create("StudyBlocks",NULL);

    

    dispatch_block_t task1 = ^(void) {

        int s = 0;

        for (int i = 0; i < Length; i++)

            s += data[i];

        sum = s;

        

        NSLog(@" >> after add: %d", sum);

        

        dispatch_semaphore_signal(taskSem);

    };

    

    dispatch_block_t task2 = ^(void) {

        dispatch_semaphore_wait(taskSem, DISPATCH_TIME_FOREVER);

        

        int s = sum;

        for (int i = 0; i < Length; i++)

            s -= data[i];

        sum = s;

        

        NSLog(@" >> after subtract: %d", sum);

        dispatch_semaphore_signal(sem);

    };

    

    dispatch_async(queue, task1);

    dispatch_async(queue, task2);

    

    // wait for the semaphore: wait until resource is ready.

    dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);

    

    dispatch_release(taskSem);

    dispatch_release(sem);

    dispatch_release(queue);

    

    /*

     在上面的代碼中,我們利用了 dispatch_queue  FIFO 特性,

     確保 task1 先於 task2 執行,而 task2 必須等待直到 task1 執行完畢纔開始幹正事,主線程又必須等待 task2 才能幹正事。

     這樣我們就可以保證先求和,再相減,然後再讓主線程運行結束這個順序。

     */

    

}


- (void)testBlock10

{

    /*

     使用 dispatch_apply 進行併發迭代:

     對於上面的求和操作,我們也可以使用 dispatch_apply 來簡化代碼的編寫:

     */

    

    initData();

    

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    

    __block int sum = 0;

    __block int *pArray = data;

    

    // iterations

    dispatch_apply(Length, queue, ^(size_t i) {

        sum += pArray[i];

    });

    

    NSLog(@" >> sum: %d", sum);

    

    dispatch_release(queue);

    

    

    /*

     注意這裏使用了全局 dispatch_queue

     dispatch_apply 的定義如下:

     dispatch_apply(size_t iterations, dispatch_queue_t queue, void (^block)(size_t));

     參數 iterations 表示迭代的次數,void (^block)(size_t)  block 循環體。這麼做與 for 循環相比有什麼好處呢?

     答案是:並行,這裏的求和是並行的,並不是按照順序依次執行求和的。

     */

}


- (void)testBlock11

{

    /*

     我們可以將完成一組相關任務的 block 添加到一個 dispatch group 中去,這樣可以在 group 中所有 block 任務都完成之後,再做其他事情。

     比如 testBlock9 中的示例也可以使用 dispatch group 實現

     */

    

    initData();

    

    __block int sum = 0;

    

    // Create a semaphore with 0 resource

    __block dispatch_semaphore_t taskSem = dispatch_semaphore_create(0);

    

    // create dispatch semaphore

    dispatch_group_t group = dispatch_group_create();

    dispatch_queue_t queue = dispatch_queue_create("StudyBlocks",NULL);

    

    dispatch_block_t task1 = ^(void) {

        int s = 0;

        for (int i = 0; i < Length; i++)

            s += data[i];

        sum = s;

        

        NSLog(@" >> after add: %d", sum);

        

        dispatch_semaphore_signal(taskSem);

    };

    

    dispatch_block_t task2 = ^(void) {

        

        dispatch_semaphore_wait(taskSem, DISPATCH_TIME_FOREVER);

        

        int s = sum;

        for (int i = 0; i < Length; i++)

            s -= data[i];

        sum = s;

        

        NSLog(@" >> after subtract: %d", sum);

    };

    

    // Fork

    dispatch_group_async(group, queue, task1);

    dispatch_group_async(group, queue, task2);

    

    // Join

    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);

    

    dispatch_release(taskSem);

    dispatch_release(queue);

    dispatch_release(group);

}


- (void)testBlock12

{

    /*

     “帶有自動變量值block中表現爲截獲自動變量

     即保存自動變量的值

     所以在執行block語法後,即使改寫block中使用的自動變量的值也不會影響block執行時自動變量的值

     該源碼就在block語法後改寫了block中自動變量valfmt

     但執行結果是:

     val = 10

     */

    int val = 10;

    const char *fmt = "val = %d\n";

    void (^blk)(void) = ^{printf(fmt, val);};

    

    val = 2;

    fmt = "These values were changed. val = %d\n";

    

    blk();  // 執行結果是:val = 10

}


- (void)testBlock13{

    

    // 雖然我們把Block Objects 異步分派到了串行隊列上,這個還是按照FIFO原則執行它的代碼

    

    __block dispatch_semaphore_t sem1 = dispatch_semaphore_create(0);

    __block dispatch_semaphore_t sem2 = dispatch_semaphore_create(0);

    __block dispatch_semaphore_t sem3 = dispatch_semaphore_create(0);

    

    dispatch_queue_t firstSerialQueue = dispatch_queue_create("com.launch.GCD.serialQueue1", 0);

    

    dispatch_async(firstSerialQueue, ^{

        NSUInteger counter = 0;

        for (counter=0; counter<5; counter++) {

            NSLog(@"First interation, counter=%d", counter);

        }

        

        dispatch_semaphore_signal(sem1);

    });

    

    dispatch_async(firstSerialQueue, ^{

        NSUInteger counter = 0;

        for (counter=0; counter<5; counter++) {

            NSLog(@"Second interation, counter=%d", counter);

        }

        dispatch_semaphore_signal(sem2);

    });

    

    dispatch_async(firstSerialQueue, ^{

        NSUInteger counter = 0;

        for (counter=0; counter<5; counter++) {

            NSLog(@"Third interation, counter=%d", counter);

        }

        dispatch_semaphore_signal(sem3);

    });

    

    dispatch_semaphore_wait(sem1, DISPATCH_TIME_FOREVER);

    dispatch_semaphore_wait(sem2, DISPATCH_TIME_FOREVER);

    dispatch_semaphore_wait(sem3, DISPATCH_TIME_FOREVER);

    

    dispatch_release(firstSerialQueue);

    dispatch_release(sem1);

    dispatch_release(sem2);

    dispatch_release(sem3);

}


- (void)testBlock14{

    

    // 雖然我們把Block Objects 異步分派到了串行隊列上,這個還是按照FIFO原則執行它的代碼

    // 但是我們可以創建多個串行隊列,不同串行隊列之間是並行的

    

    __block dispatch_semaphore_t sem1 = dispatch_semaphore_create(0);

    __block dispatch_semaphore_t sem2 = dispatch_semaphore_create(0);

    __block dispatch_semaphore_t sem3 = dispatch_semaphore_create(0);

    

    dispatch_queue_t firstSerialQueue1 = dispatch_queue_create("com.launch.GCD.serialQueue1", 0);

    dispatch_queue_t firstSerialQueue2 = dispatch_queue_create("com.launch.GCD.serialQueue2", 0);

    dispatch_queue_t firstSerialQueue3 = dispatch_queue_create("com.launch.GCD.serialQueue3", 0);

    

    dispatch_async(firstSerialQueue1, ^{

        NSUInteger counter = 0;

        for (counter=0; counter<5; counter++) {

            NSLog(@"First interation, counter=%d", counter);

        }

        

        dispatch_semaphore_signal(sem1);

    });

    

    dispatch_async(firstSerialQueue2, ^{

        NSUInteger counter = 0;

        for (counter=0; counter<5; counter++) {

            NSLog(@"Second interation, counter=%d", counter);

        }

        dispatch_semaphore_signal(sem2);

    });

    

    dispatch_async(firstSerialQueue3, ^{

        NSUInteger counter = 0;

        for (counter=0; counter<5; counter++) {

            NSLog(@"Third interation, counter=%d", counter);

        }

        dispatch_semaphore_signal(sem3);

    });

    

    dispatch_semaphore_wait(sem1, DISPATCH_TIME_FOREVER);

    dispatch_semaphore_wait(sem2, DISPATCH_TIME_FOREVER);

    dispatch_semaphore_wait(sem3, DISPATCH_TIME_FOREVER);

    

    dispatch_release(firstSerialQueue1);

    dispatch_release(firstSerialQueue2);

    dispatch_release(firstSerialQueue3);

    dispatch_release(sem1);

    dispatch_release(sem2);

    dispatch_release(sem3);

}



static dispatch_once_t onceToken;

void (^executedOnlyOnce)(void) = ^{

    static NSUInteger numberOfEntries = 0;

    numberOfEntries++;

    NSLog(@"Executed %d time(s)", numberOfEntries);

};


- (void)testBlock15{

    

    // 一個任務最多隻執行一次

    dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    

    

    dispatch_once(&onceToken, ^{

        dispatch_async(concurrentQueue, executedOnlyOnce);

    });

    

    dispatch_once(&onceToken, ^{

        dispatch_async(concurrentQueue, executedOnlyOnce);

    });

    

    

    // 稍緩線程退出

    NSUInteger count= 0;

    while (count++ < 3) {

        

        sleep(1);

    }

}


- (void)testBlock16{

    

    // 利用dispatch_once實現單例

    /*

     @interface SingletonSample : NSObject

     

     + (id)ShareInstance;

     @end

     

     @implementation SingletonSample

     + (id)ShareInstance{

     static SingletonSample *SharedInstance = nil;

     static dispatch_once_t onceToken;

     dispatch_once(&onceToken, ^{

     SharedInstance = [[SingletonSample alloc] init];

     });

     

     return SharedInstance;

     }

     @end

     */

    

    SingletonSample *obj1 = [SingletonSample ShareInstance];

    SingletonSample *obj2 = [SingletonSample ShareInstance];

    

    NSLog(@"obj1=%@, obj2=%@", obj1, obj2);

    STAssertEquals(obj1, obj2, nil);

    

}



- (void)testBlock17{

    

    // 利用GCD延時後執行任務

    

    double delayInsenconds = 2.0;

    dispatch_time_t delayInNanoSeconds = dispatch_time(DISPATCH_TIME_NOW, delayInsenconds * NSEC_PER_SEC);

    dispatch_queue_t concurrentQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    NSLog(@"testBlock17");

    dispatch_after(delayInNanoSeconds, concurrentQueue, ^(void){

        NSLog(@"Now do work in dispatch_after");

    });

    

    // 稍緩線程退出

    NSUInteger count= 0;

    while (count++ < 5) {

        

        sleep(1);

    }

}


@end

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章