多線程GCD筆記

  • 同步函數 + 主隊列
  • 異步函數 + 主隊列
  • 同步函數 + 串行隊列
  • 異步函數 + 串行隊列
  • 同步函數 + 并發隊列
  • 異步函數 + 并發隊列
  • 線程間通信
  • dispatch_barrier_async(柵欄)
  • dispatch_after 延遲執行
  • dispatch_apply 多線程遍歷
  • dispatch_once
  • dispatch_async_f
  • dispatch_group
  • dispatch_source定時器
  • dispatch_group_enter/dispatch_group_leave/dispatch_group_notify
  • 同步函數 + 主隊列:
    執行dispatch_sync時主線程堵塞
    執行結果:Thread ----- begin
    -(void)thread {
NSLog(@"Thread ----- begin");
// 1.獲得主隊列
dispatch_queue_t queue = dispatch_get_main_queue();
// 2.將任務加入隊列
dispatch_sync(queue, ^{
    NSLog(@"%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");

}

  • 異步函數 + 主隊列:只在主線程中執行任務

因為是在主線程中,所以1-7任務按順序執行
執行結果:
Thread ----- begin
Thread ----- end
1-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
2-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
3-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
4-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
5-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
6-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
7-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
-(void)thread {

NSLog(@"Thread ----- begin");
// 1.獲得主隊列
dispatch_queue_t queue = dispatch_get_main_queue();

// 2.將任務加入隊列
dispatch_async(queue, ^{
    NSLog(@"1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"2-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"3-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    sleep(1.0);
    NSLog(@"4-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"5-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"6-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"7-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");

}

  • 同步函數 + 串行隊列:不會開啟新的線程,thread方法所在的線程是main。任務是串行的,執行完1任務,再執2任務,按順序執行

執行結果:
Thread ----- begin
1-----<NSThread: 0x7faf10604e80>{number = 1, name = main}
2-----<NSThread: 0x7faf10604e80>{number = 1, name = main}
Thread ----- end
-(void)thread {

NSLog(@"Thread ----- begin");
// 1.創建串行隊列
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);

// 2.將任務加入隊列
dispatch_sync(queue, ^{
    NSLog(@"1-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
    NSLog(@"2-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");

}

  • 異步函數 + 串行隊列:會開啟新的線程,但是任務是串行的,執行完1任務,再執行2任務,按順序執行
    執行結果:

Thread ----- begin
Thread ----- end
1-----<NSThread: 0x7f917044f030>{number = 3, name = (null)}
2-----<NSThread: 0x7f917044f030>{number = 3, name = (null)}
-(void)thread {

NSLog(@"Thread ----- begin");
// 1.創建串行隊列
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);

// 2.將任務加入隊列
dispatch_async(queue, ^{
    NSLog(@"1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"2-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");

}

  • 同步函數 + 并發隊列:不會開啟新的線程,在thread方法所在的線程中,按順序執行1,2任務

DISPATCH_QUEUE_PRIORITY_DEFAULT:默認優先級
執行結果:
Thread ----- begin
1-----<NSThread: 0x7fd66ae16720>{number = 3, name = thread1}
2-----<NSThread: 0x7fd66ae16720>{number = 3, name = thread1}
Thread ----- end
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(thread) object:nil];
thread.name = @"thread1";
[thread start];

}

-(void)thread{

NSLog(@"Thread ----- begin");
// 1.獲得全局的并發隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// 2.將任務加入隊列
dispatch_sync(queue, ^{
    NSLog(@"1-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
    NSLog(@"2-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");

}

  • 異步函數 + 并發隊列:可以同時開啟多條線程

執行結果:
Thread ----- begin
Thread ----- end
1-----<NSThread: 0x7fd86b706bc0>{number = 3, name = (null)}
2-----<NSThread: 0x7fd86b625900>{number = 2, name = (null)}
1-----<NSThread: 0x7fd86b706bc0>{number = 3, name = (null)}
2-----<NSThread: 0x7fd86b625900>{number = 2, name = (null)}
-(void)thread {

NSLog(@"Thread ----- begin");
// 1.獲得全局的并發隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// 2.將任務加入隊列
dispatch_async(queue, ^{
    for (NSInteger i = 0; i<2; i++) {
        NSLog(@"1-----%@", [NSThread currentThread]);
    }
});
dispatch_async(queue, ^{
    for (NSInteger i = 0; i<2; i++) {
        NSLog(@"2-----%@", [NSThread currentThread]);
    }
});
NSLog(@"Thread ----- end");

}

線程間通信

-(void)thread {

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    //耗時操作
    dispatch_async(dispatch_get_main_queue(), ^{
        //回到主線程,更新UI
    });
});

dispatch_barrier_async:

dispatch_barrier_async,可以翻譯成柵欄(barrier)
barrier作為流程控制的一種方式是用在并行環境當中。

以barrier任務為分界線,先執行barrier之前的任務1,2(1,2執行順序不確定),在執行3,4(3,4執行順序不確定)
執行結果:
----2-----<NSThread: 0x7f9982503140>{number = 6, name = (null)}
----1-----<NSThread: 0x7f9982748d90>{number = 5, name = (null)}
----barrier-----<NSThread: 0x7f9982748d90>{number = 5, name = (null)}
----3-----<NSThread: 0x7f9982748d90>{number = 5, name = (null)}
----4-----<NSThread: 0x7f9982503140>{number = 6, name = (null)}
-(void)barrier {

dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{
    NSLog(@"----1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"----2-----%@", [NSThread currentThread]);
});

dispatch_barrier_async(queue, ^{
    NSLog(@"----barrier-----%@", [NSThread currentThread]);
});

dispatch_async(queue, ^{
    NSLog(@"----3-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"----4-----%@", [NSThread currentThread]);
});

}

注釋掉dispatch_barrier_async后任務1-4執行順序無序
執行結果:
----1-----<NSThread: 0x7f94d3725df0>{number = 3, name = (null)}
----4-----<NSThread: 0x7f94d379a910>{number = 5, name = (null)}
----3-----<NSThread: 0x7f94d3463810>{number = 4, name = (null)}
----2-----<NSThread: 0x7f94d344f320>{number = 2, name = (null)}
-(void)barrier {

dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{
    NSLog(@"----1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"----2-----%@", [NSThread currentThread]);
});

// dispatch_barrier_async(queue, ^{
// NSLog(@"----barrier-----%@", [NSThread currentThread]);
// });

dispatch_async(queue, ^{
    NSLog(@"----3-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
    NSLog(@"----4-----%@", [NSThread currentThread]);
});

}

延遲執行

#define DISPATCH_TIME_NOW (0ull) : unsigned long long 類型的0
#define NSEC_PER_SEC 1000000000ull : unsigned long long 類型的1000000000
dispatch_after:不是一定時間后執行相應的任務,而是一定時間后,將執行的操作加入到隊列中(隊列里面再分配執行的時間)所以在比如主線程每隔1/60秒執行的RunLoop,Block最快在2秒后執行,最慢在 2+1/60秒后執行。

非阻塞的執行方式,延時2秒,dispatch_get_main_queue()主線程中執行

    CGFloat t = 2.0;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(t * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

    });
  • Swift延時執行方法
    let time: NSTimeInterval = 2.0
    let delay = dispatch_time(DISPATCH_TIME_NOW,
    Int64(time * Double(NSEC_PER_SEC)))
    dispatch_after(delay, dispatch_get_main_queue()) {

    }
    
  • 其他延時方法:

此方式要求必須在主線程中執行,否則無效。
是一種非阻塞的執行方式,
可以通過NSTimer類的- (void)invalidate;取消執行。
repeats:是否重復執行
-(void)timer{

 [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(running) userInfo:nil repeats:NO];  

}

此方式要求必須在主線程中執行,否則無效。
是一種非阻塞的執行方式
-(void)timer{

 [self performSelector:@selector(running) withObject:nil afterDelay:2.0f];

}

dispatch_apply

第一個參數是迭代次數(這里便利10次),第二個是所在的隊列(queue),第三個是當前索引(index)
dispatch_apply 和 dispatch_apply_f 是同步函數,會阻塞當前線程直到所有循環迭代執行完成。當提交到并發queue時,循環迭代的執行順序是不確定的
執行結果:
<NSThread: 0x7f9f40c08b20>{number = 1, name = main}, arr[0]:11
<NSThread: 0x7f9f40e10660>{number = 3, name = (null)}, arr[1]:12
<NSThread: 0x7f9f40e0d2f0>{number = 4, name = (null)}, arr[3]:14
<NSThread: 0x7f9f40f21450>{number = 2, name = (null)}, arr[2]:13
<NSThread: 0x7f9f40e10660>{number = 3, name = (null)}, arr[5]:16
<NSThread: 0x7f9f40e0d2f0>{number = 4, name = (null)}, arr[6]:17
<NSThread: 0x7f9f40c08b20>{number = 1, name = main}, arr[4]:15
<NSThread: 0x7f9f40f21450>{number = 2, name = (null)}, arr[7]:18
<NSThread: 0x7f9f40e10660>{number = 3, name = (null)}, arr[8]:19
<NSThread: 0x7f9f40e0d2f0>{number = 4, name = (null)}, arr[9]:20

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSArray *arr = @[@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20"];
dispatch_apply(arr.count, queue, ^(size_t index) {
    NSLog(@"%@, arr[%zu]:%@", [NSThread currentThread], index, arr[index]);
});

dispatch_once

dispatch_once不僅意味著代碼僅會被運行一次,而且還是線程安全的,這就意味著你不需要使用諸如@synchronized之類的來防止使用多個線程或者隊列時不同步的問題。

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    //程序運行期間只會執行一次
});

利用dispatch_once創建單例模式
static id _instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone{

static dispatch_once_t onceToken;//記錄是否執行了block
dispatch_once(&onceToken, ^{
    _instance = [super allocWithZone:zone];
});
return _instance;

}
+(instancetype)shareInstance{

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    _instance = [[self alloc] init];
});
return _instance;

}
-(id)copyWithZone:(NSZone *)zone{

return _instance;

}

dispatch_async_f

一般用dispatch_async(block)。dispatch_async_f(函數)
執行結果:dsafasd

-(void)asuncf{

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSString *str = @"dsafasd";
dispatch_async_f(queue, (__bridge void *)(str), download);

}

void download(void * data)
{
NSLog(@"%@", data);
}

dispatch_group

因為是在并行隊列上執行,追加字符串的2個任務執行順不不確定,當并行隊列全部執行完成后,最后到dispatch_group_notify執行操作。

執行結果:123456
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, copy) NSString *str;
@end
-(void)group {

// 獲取全局列組
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 創建一個隊列組
dispatch_group_t group = dispatch_group_create();
self.str = @"";
dispatch_group_async(group, queue, ^{
   self.str = [self.str stringByAppendingString:@"123"];
});

dispatch_group_async(group, queue, ^{
    self.str = [self.str stringByAppendingString:@"456"];
});

dispatch_group_notify(group, queue, ^{
    NSLog(@"%@", self.str);
    dispatch_async(dispatch_get_main_queue(), ^{
        //主線程操作
    });
});

}

dispatch_source定時器

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
dispatch_queue_t queue = dispatch_get_main_queue();

// 創建一個定時器(dispatch_source_t本質還是個OC對象)
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

// 設置定時器的各種屬性(幾時開始任務,每隔多長時間執行一次)
// GCD的時間參數,一般是納秒(1秒 == 10的9次方納秒)
// 何時開始執行第一個任務
// dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC) 比當前時間晚3秒
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
dispatch_source_set_timer(self.timer, start, interval, 0);

// 設置回調
dispatch_source_set_event_handler(self.timer, ^{
    NSLog(@"------------%@", [NSThread currentThread]);
});

// 啟動定時器
dispatch_resume(self.timer);
}

dispatch_group_enter/dispatch_group_leave/dispatch_group_notify

    目的:所有操作執行完成后再執行dispatch_group_notify內的任務
    // 1.創建一個組
    let group = dispatch_group_create()
    // 2.將操作添加到組中
    dispatch_group_enter(group)
    //3.要執行的操作。。。。
    // 4.離開當前組
    dispatch_group_leave(group)
    //5.所有操作完成后執行
    dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,527評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,687評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,640評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,957評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,682評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,011評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,009評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,183評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,714評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,435評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,665評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,148評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,838評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,251評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,588評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,379評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,627評論 2 380

推薦閱讀更多精彩內容