您的位置:首页 > 理论基础 > 计算机网络

第02天多线程网络:(02):GCD栅栏函数

2017-04-17 00:00 295 查看
#####一、GCD栅栏函数

1.用来控制多线程的执行顺序
2.异步:(dispatch_barrier_sync) 同步 本来就是串行执行的
3.栅栏函数不能使用全局的并发队列
✅写法: dispatch_queue_t queue = dispatch_queue_create("download", DISPATCH_QUEUE_PRIORITY_DEFAULT);
❌写法: dispatch_queue_t queue =  dispatch_get_global_queue(0, 0);


code

/**
各个队列的执行效果

并发队列      手动创建的串行队列               主队列
同步(sync)     没有开启新线程      没有开启新线程      (如果在子线程)没有开启新线程 (主线程)形成死锁
串行执行任务        串行执行任务               串行执行任务

异步(async)     开启新线程(记)      开启新线程(记)            没有开启新线程
并发执行           串行执行                  串行执行任务
*/
#import "ViewController.h"

@interface ViewController ()
/** <#注释#> */
@property (nonatomic,assign) NSInteger s;
@end

@implementation ViewController
- (void)text
{

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 0.获取全局的并发队列
//    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_queue_t queue =  dispatch_get_global_queue(0, 0);
// 参数1: 标签, 参数2: 队列
dispatch_queue_t queue = dispatch_queue_create("download", DISPATCH_QUEUE_PRIORITY_DEFAULT);

// 1.异步函数
dispatch_async(queue, ^{
for (NSInteger i = 0; i<100; i++) {
NSLog(@"download1 ---%@",[NSThread currentThread]);
}
});

dispatch_async(queue, ^{
for (NSInteger i = 0; i<100; i++) {
NSLog(@"download2 ---%@",[NSThread currentThread]);
}

});

// 栅栏函数
dispatch_barrier_sync(queue, ^{
NSLog(@"----");

});

dispatch_async(queue, ^{
for (NSInteger i = 0; i<100; i++) {
NSLog(@"download3 ---%@",[NSThread currentThread]);
}    });

#pragma mark GCD栅栏函数 : 用来控制多线程的执行顺序 异步:(dispatch_barrier_sync) 同步 本来就是串行执行的

}

@end
/**
控制台
2017-05-05 17:06:10.608 02.GCD栅栏函数[17435:264432] download1 ---<NSThread: 0x60800007b780>{number = 4, name = (null)}
2017-05-05 17:06:10.608 02.GCD栅栏函数[17435:264432] download2 ---<NSThread: 0x60800007b780>{number = 4, name = (null)}
2017-05-05 17:06:10.608 02.GCD栅栏函数[17435:263192] ----
2017-05-05 17:06:10.609 02.GCD栅栏函数[17435:264432] download3 ---<NSThread: 0x60800007b780>{number = 4, name = (null)}
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Objective-C 多线程