IOS-GCDマルチスレッド
4861 ワード
同期&非同期:
: ; 。
シリアル&パラレル:
dispatch_get_main_queue -->
dispatch_get_global_queue --> ( )
簡単な例:
dispatch_async(dispatch_get_global_queue(0,0), ^{
NSLog(@"Task Thread!");
[NSThread sleepTimeInterval:3];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@" UI Thread!")
});
});
カスタムスレッド:
シリアル:同期スレッドであるカスタムスレッドを作成します.次の2つのdispatch_を実行します.asyncは、実際には同じスレッドであり、task 1とtask 2は前後順に実行されます.デフォルトNULLはDISPATCH_ですQUEUE_SEARIAL
dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", NULL);
dispatch_async(queue, ^{
NSLog(@"task 1");
[NSthread sleepForTimeInterval:2];
NSLog(@"task 1 over");
});
dispatch_async(queue, ^{
NSLog(@"task 2");
[NSthread sleepForTimeInterval:2];
NSLog(@"task 2 over");
});
パラレル:DISPATCH_QUEUE_CONCURRENTパラメータは、並列キューを作成します.
dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"task 1");
[NSthread sleepForTimeInterval:2];
NSLog(@"task 1 over");
});
dispatch_async(queue, ^{
NSLog(@"task 2");
[NSthread sleepForTimeInterval:2];
NSLog(@"task 2 over");
});
GCD_グループの使用:
dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", DISPATCH_QUEUE_CONCURRENT);
// group
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
NSLog(@"task 1");
[NSthread sleepForTimeInterval:2];
NSLog(@"task 1 over");
});
dispatch_group_async(group, queue, ^{
NSLog(@"task 2");
[NSthread sleepForTimeInterval:2];
NSLog(@"task 2 over");
});
dispatch_group_notify(group, queue, ^{
NSLog(@"All task over!");
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@" UI Thread!")
});
});
非同期スレッド制御方法:
dispatch_queue_t queue = dispatch_queue_create(@"gcd_queue", DISPATCH_QUEUE_CONCURRENT);
// group
dispatch_group_t group = dispatch_group_create();
// group
dispatch_group_enter(group);
.
. //
.
// group
dispatch_group_leave(group);