多线程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阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容