iOS底层day9 - 多线程

进程 & 线程

  • 提到线程,那就不得不提CPU,现代的CPU有一个很重要的特性,就是时间片,每一个获得CPU的任务只能运行一个时间片规定的时间。
  • 其实线程对操作系统来说就是一段代码以及运行时数据。操作系统会为每个线程保存相关的数据,当接收到来自CPU的时间片中断事件时,就会按一定规则从这些线程中选择一个,恢复它的运行时数据,这样CPU就可以继续执行这个线程了。
  • 也就是其实就单核CUP而言,并没有办法实现真正意义上的并发执行,只是CPU快速地在多条线程之间调度,CPU调度线程的时间足够快,就造成了多线程并发执行的假象。并且就单核CPU而言多线程可以解决线程阻塞的问题,但是其本身运行效率并没有提高,多CPU的并行运算才真正解决了运行效率问题。
  • 系统中正在运行的每一个应用程序都是一个进程,每个进程系统都会分配给它独立的内存运行。也就是说,在iOS系统中中,每一个应用都是一个进程。
  • 一个进程的所有任务都在线程中进行,因此每个进程至少要有一个线程,也就是主线程。那多线程其实就是一个进程开启多条线程,让所有任务并发执行。
  • 多线程在一定意义上实现了进程内的资源共享,以及效率的提升。同时,在一定程度上相对独立,它是程序执行流的最小单元,是进程中的一个实体,是执行程序最基本的单元,有自己栈和寄存器

同步异步 & 串行并行

同步与异步的区别:具不具备开线程的能力
串行与并行:可不可以同时执行多个任务,异步是多个任务并行的前提条件

举个栗子 & 同步异步

    dispatch_queue_t queue = dispatch_queue_create("myquere", DISPATCH_QUEUE_SERIAL);
    dispatch_sync(queue, ^{
        for (int i = 0; i < 10; i ++) {
            NSLog(@"queue4 -- %d -----%@",i,[NSThread currentThread]);
        }
    });
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i ++) {
            NSLog(@"queue5 -- %d -----%@",i,[NSThread currentThread]);
        }
    });

打印结果

2018-11-07 08:51:58.130210+0800 09-线程[1136:19292] queue4 -- 0 -----{number = 1, name = main}
2018-11-07 08:51:58.130486+0800 09-线程[1136:19292] queue4 -- 1 -----{number = 1, name = main}
2018-11-07 08:51:58.130669+0800 09-线程[1136:19292] queue4 -- 2 -----{number = 1, name = main}
2018-11-07 08:51:58.130822+0800 09-线程[1136:19292] queue4 -- 3 -----{number = 1, name = main}
2018-11-07 08:51:58.131010+0800 09-线程[1136:19292] queue4 -- 4 -----{number = 1, name = main}
2018-11-07 08:51:58.131154+0800 09-线程[1136:19292] queue4 -- 5 -----{number = 1, name = main}
2018-11-07 08:51:58.131290+0800 09-线程[1136:19292] queue4 -- 6 -----{number = 1, name = main}
2018-11-07 08:51:58.131423+0800 09-线程[1136:19292] queue4 -- 7 -----{number = 1, name = main}
2018-11-07 08:51:58.131548+0800 09-线程[1136:19292] queue4 -- 8 -----{number = 1, name = main}
2018-11-07 08:51:58.132504+0800 09-线程[1136:19292] queue4 -- 9 -----{number = 1, name = main}
2018-11-07 08:51:58.133260+0800 09-线程[1136:19344] queue5 -- 0 -----{number = 3, name = (null)}
2018-11-07 08:51:58.133849+0800 09-线程[1136:19344] queue5 -- 1 -----{number = 3, name = (null)}
2018-11-07 08:51:58.174407+0800 09-线程[1136:19344] queue5 -- 2 -----{number = 3, name = (null)}
2018-11-07 08:51:58.174590+0800 09-线程[1136:19344] queue5 -- 3 -----{number = 3, name = (null)}
2018-11-07 08:51:58.175140+0800 09-线程[1136:19344] queue5 -- 4 -----{number = 3, name = (null)}
2018-11-07 08:51:58.175492+0800 09-线程[1136:19344] queue5 -- 5 -----{number = 3, name = (null)}
2018-11-07 08:51:58.176540+0800 09-线程[1136:19344] queue5 -- 6 -----{number = 3, name = (null)}
2018-11-07 08:51:58.176792+0800 09-线程[1136:19344] queue5 -- 7 -----{number = 3, name = (null)}
2018-11-07 08:51:58.176952+0800 09-线程[1136:19344] queue5 -- 8 -----{number = 3, name = (null)}
2018-11-07 08:51:58.177108+0800 09-线程[1136:19344] queue5 -- 9 -----{number = 3, name = (null)}

异步下,开启了一个子线程number 3 去执行任务

举个栗子 & 串行并行

异步串行:

    dispatch_queue_t queue2 = dispatch_queue_create("myqueue", DISPATCH_QUEUE_SERIAL);
    for (int i = 0; i < 10; i ++) {
        dispatch_async(queue2, ^{
            NSLog(@"queue5 -- %d -----%@",i,[NSThread currentThread]);
        });
    }

执行结果:

2018-11-07 09:13:22.052006+0800 09-线程[2109:42825] queue5 -- 0 -----{number = 3, name = (null)}
2018-11-07 09:13:22.052427+0800 09-线程[2109:42825] queue5 -- 1 -----{number = 3, name = (null)}
2018-11-07 09:13:22.052618+0800 09-线程[2109:42825] queue5 -- 2 -----{number = 3, name = (null)}
2018-11-07 09:13:22.052806+0800 09-线程[2109:42825] queue5 -- 3 -----{number = 3, name = (null)}
2018-11-07 09:13:22.053263+0800 09-线程[2109:42825] queue5 -- 4 -----{number = 3, name = (null)}
2018-11-07 09:13:22.053826+0800 09-线程[2109:42825] queue5 -- 5 -----{number = 3, name = (null)}
2018-11-07 09:13:22.053981+0800 09-线程[2109:42825] queue5 -- 6 -----{number = 3, name = (null)}
2018-11-07 09:13:22.054201+0800 09-线程[2109:42825] queue5 -- 7 -----{number = 3, name = (null)}
2018-11-07 09:13:22.054602+0800 09-线程[2109:42825] queue5 -- 8 -----{number = 3, name = (null)}
2018-11-07 09:13:22.054895+0800 09-线程[2109:42825] queue5 -- 9 -----{number = 3, name = (null)}

异步并行:

    dispatch_queue_t queue = dispatch_queue_create("myqueue", DISPATCH_QUEUE_CONCURRENT);
    for (int i = 0; i < 10; i ++) {
        dispatch_async(queue, ^{
            NSLog(@"queue6 -- %d -----%@",i,[NSThread currentThread]);
        });
    }

执行结果:

2018-11-07 09:14:53.988564+0800 09-线程[2145:44288] queue6 -- 0 -----{number = 3, name = (null)}
2018-11-07 09:14:53.988575+0800 09-线程[2145:44289] queue6 -- 3 -----{number = 6, name = (null)}
2018-11-07 09:14:53.988569+0800 09-线程[2145:44290] queue6 -- 2 -----{number = 5, name = (null)}
2018-11-07 09:14:53.988607+0800 09-线程[2145:44287] queue6 -- 1 -----{number = 4, name = (null)}
2018-11-07 09:14:53.988889+0800 09-线程[2145:44288] queue6 -- 4 -----{number = 3, name = (null)}
2018-11-07 09:14:53.988926+0800 09-线程[2145:44289] queue6 -- 5 -----{number = 6, name = (null)}
2018-11-07 09:14:53.989017+0800 09-线程[2145:44314] queue6 -- 6 -----{number = 7, name = (null)}
2018-11-07 09:14:53.989041+0800 09-线程[2145:44315] queue6 -- 7 -----{number = 8, name = (null)}
2018-11-07 09:14:53.989114+0800 09-线程[2145:44316] queue6 -- 8 -----{number = 10, name = (null)}
2018-11-07 09:14:53.989114+0800 09-线程[2145:44317] queue6 -- 9 -----{number = 9, name = (null)}

异步并行下,开启了多个线程去同时执行任务

线程死锁

先来看以下代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    dispatch_sync(dispatch_get_main_queue(), ^{
        NSLog(@"1");
    });
}

这里,viewDidLoad^{ NSLog(@"1") },为两个任务AB,首先A在主队列,并且在主线程执行,这时候主队列加入了任务B,于是主队列的顺序就是 A执行完、执行B,我们这里又是用串行sync执行,需要block的内容执行完毕(B执行完毕),任务A才执行完毕,所以这里就出现了互相等待的死锁情况。
这里,我们可以把dispatch_get_main_queue() 换成另外一个队列,就不会出现死锁了

线程锁

当我们使用多线程时,操作同一个任务的时候,是有可能出现线程不安全的问题:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.money = 200;
    
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i ++) {
            [self saveMoney];
        }
    });
    
    dispatch_async(queue, ^{
        for (int i = 0; i < 10; i ++) {
            [self drawMoney];
        }
    });
 
}

- (void)saveMoney {
    int money = self.money;
    sleep(.2);
    money += 50;
    self.money = money;
    
    NSLog(@"存钱50 - 当前金额为:%d , 当前线程为 %@",self.money,[NSThread currentThread]);
}

- (void)drawMoney {
    int money = self.money;
    sleep(.2);
    money -= 20;
    self.money = money;
    
    NSLog(@"取钱20 - 当前金额为:%d , 当前线程为 %@",self.money,[NSThread currentThread]);
}

打印结果:

2018-11-07 15:11:20.045459+0800 09-线程[4708:212472] 取钱20 - 当前金额为:180 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.045453+0800 09-线程[4708:212475] 存钱50 - 当前金额为:250 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.045730+0800 09-线程[4708:212475] 存钱50 - 当前金额为:230 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.045797+0800 09-线程[4708:212472] 取钱20 - 当前金额为:210 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.046415+0800 09-线程[4708:212475] 存钱50 - 当前金额为:260 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.046626+0800 09-线程[4708:212472] 取钱20 - 当前金额为:240 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.046797+0800 09-线程[4708:212475] 存钱50 - 当前金额为:290 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.046900+0800 09-线程[4708:212472] 取钱20 - 当前金额为:270 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.047037+0800 09-线程[4708:212475] 存钱50 - 当前金额为:320 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.048622+0800 09-线程[4708:212472] 取钱20 - 当前金额为:300 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.049292+0800 09-线程[4708:212475] 存钱50 - 当前金额为:350 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.049894+0800 09-线程[4708:212472] 取钱20 - 当前金额为:330 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.050160+0800 09-线程[4708:212475] 存钱50 - 当前金额为:380 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.051462+0800 09-线程[4708:212472] 取钱20 - 当前金额为:360 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.051761+0800 09-线程[4708:212475] 存钱50 - 当前金额为:410 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.052363+0800 09-线程[4708:212472] 取钱20 - 当前金额为:390 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.052789+0800 09-线程[4708:212475] 存钱50 - 当前金额为:440 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.053310+0800 09-线程[4708:212472] 取钱20 - 当前金额为:420 , 当前线程为 {number = 4, name = (null)}
2018-11-07 15:11:20.053921+0800 09-线程[4708:212475] 存钱50 - 当前金额为:470 , 当前线程为 {number = 3, name = (null)}
2018-11-07 15:11:20.054219+0800 09-线程[4708:212472] 取钱20 - 当前金额为:450 , 当前线程为 {number = 4, name = (null)}

照理说,我们进行了10次的存钱取钱,最终得到的结果应该是500块钱,可是这里却没有,原因是因为我们在存钱/取钱的时候,是同时进行的,假如当第一次取出的钱self.money是200,这时候进行了存钱操作,则记录为250,但是取钱又是同时进行的,在存钱操作没有做完的时候,取钱操作取出的钱也是200,进行取钱操作后记录为180,这时候无论谁把钱赋值给self.money都是错误的,所以这里存钱和取钱的操作应该是分开进行的,于是我们就有了线程锁的概念。
线程锁有很多种,包括:

  • OSSpinLock : iOS10之前的线程锁,现在已经不安全了,会出现优先级反转的问题 (自旋锁)
  • os_unfair_lock : iOS10之后替换OSSpinLock
  • pthread_mutex: 跨平台锁,可传入属性,作为递归锁
  • dispatch_semaphore (信号量): 控制线程的并发数量
  • NSConditionLock:线程先后执行顺序
  • @synchroized :对象锁,传入的同一个对象就可以实现同步,性能较差(封装pthread_mutex),但是用法最简单
    …………
    性能排序

线程锁用法

这里主要讲 dispatch_semaphore、 @synchroized、NSConditionLock的用法

dispatch_semaphore

- (void)viewDidLoad {
    [super viewDidLoad];
    // 传入的5表示控制线程最大的并发数量为5
    self.semaphore = dispatch_semaphore_create(5);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (int i = 0; i < 20; i++) {
        [[[NSThread alloc] initWithTarget:self selector:@selector(semaphoreTest) object:nil] start];
    }
}
- (void)semaphoreTest {
    // 如果信号量的值 > 0,就让信号量的值减1,然后继续往下执行代码
    // 如果信号量的值 <= 0,就会休眠等待,直到信号量的值变成>0,就让信号量的值减1,然后继续往下执行代码
    dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
    
    sleep(2);
    NSLog(@"test - %@", [NSThread currentThread]);
    
    // 让信号量的值+1
    dispatch_semaphore_signal(self.semaphore);
}

打印结果:

2018-11-08 09:42:43.756944+0800 09-线程[1815:57093] test - {number = 4, name = (null)}
2018-11-08 09:42:43.756940+0800 09-线程[1815:57094] test - {number = 5, name = (null)}
2018-11-08 09:42:43.756937+0800 09-线程[1815:57096] test - {number = 7, name = (null)}
2018-11-08 09:42:43.757042+0800 09-线程[1815:57095] test - {number = 6, name = (null)}
2018-11-08 09:42:43.757078+0800 09-线程[1815:57092] test - {number = 3, name = (null)}
2018-11-08 09:42:45.763554+0800 09-线程[1815:57097] test - {number = 8, name = (null)}
2018-11-08 09:42:45.763560+0800 09-线程[1815:57099] test - {number = 10, name = (null)}
2018-11-08 09:42:45.763649+0800 09-线程[1815:57098] test - {number = 9, name = (null)}
2018-11-08 09:42:45.763702+0800 09-线程[1815:57100] test - {number = 11, name = (null)}
2018-11-08 09:42:45.763807+0800 09-线程[1815:57101] test - {number = 12, name = (null)}
2018-11-08 09:42:47.770115+0800 09-线程[1815:57104] test - {number = 15, name = (null)}
2018-11-08 09:42:47.770243+0800 09-线程[1815:57103] test - {number = 14, name = (null)}
2018-11-08 09:42:47.770122+0800 09-线程[1815:57102] test - {number = 13, name = (null)}
2018-11-08 09:42:47.770250+0800 09-线程[1815:57106] test - {number = 17, name = (null)}
2018-11-08 09:42:47.770243+0800 09-线程[1815:57105] test - {number = 16, name = (null)}
2018-11-08 09:42:49.775898+0800 09-线程[1815:57107] test - {number = 18, name = (null)}
2018-11-08 09:42:49.775904+0800 09-线程[1815:57108] test - {number = 19, name = (null)}
2018-11-08 09:42:49.775948+0800 09-线程[1815:57109] test - {number = 20, name = (null)}
2018-11-08 09:42:49.776003+0800 09-线程[1815:57111] test - {number = 22, name = (null)}
2018-11-08 09:42:49.776007+0800 09-线程[1815:57110] test - {number = 21, name = (null)}

每次相差2秒执行5个线程的操作,如果要做成同步锁的话,传入的信号量的值为1就好了。
@synchroized

- (void)synchronizedTestTest
{
    @synchronized([self class]) {
        sleep(1);
        NSLog(@"123 - %@",[NSThread currentThread]);
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (int i = 0; i < 20; i++) {
        [[[NSThread alloc] initWithTarget:self selector:@selector(synchronizedTestTest) object:nil] start];
    }
}

打印结果

2018-11-08 09:52:08.104731+0800 09-线程[1990:66615] 123 - {number = 3, name = (null)}
2018-11-08 09:52:09.107712+0800 09-线程[1990:66616] 123 - {number = 4, name = (null)}
2018-11-08 09:52:10.112815+0800 09-线程[1990:66617] 123 - {number = 5, name = (null)}
2018-11-08 09:52:11.118213+0800 09-线程[1990:66618] 123 - {number = 6, name = (null)}
2018-11-08 09:52:12.123081+0800 09-线程[1990:66619] 123 - {number = 7, name = (null)}
2018-11-08 09:52:13.124789+0800 09-线程[1990:66620] 123 - {number = 8, name = (null)}
2018-11-08 09:52:14.130562+0800 09-线程[1990:66621] 123 - {number = 9, name = (null)}
2018-11-08 09:52:15.133153+0800 09-线程[1990:66622] 123 - {number = 10, name = (null)}

@synchronized 锁的对象可以是任何对象,只要在需要的场景使用相同的一个对象作为锁就可以了

NSConditionLock


- (void)viewDidLoad {
    [super viewDidLoad];
 self.conditionLock = [[NSConditionLock alloc] initWithCondition:1];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[[NSThread alloc] initWithTarget:self selector:@selector(__one) object:nil] start];
    
    [[[NSThread alloc] initWithTarget:self selector:@selector(__two) object:nil] start];
    
    [[[NSThread alloc] initWithTarget:self selector:@selector(__three) object:nil] start];
}

- (void)__one
{
    [self.conditionLock lock];
    
    NSLog(@"__one");
    sleep(1);
    
    [self.conditionLock unlockWithCondition:2];
}

- (void)__two
{
    [self.conditionLock lockWhenCondition:2];
    
    NSLog(@"__two");
    sleep(1);
    
    [self.conditionLock unlockWithCondition:3];
}

- (void)__three
{
    [self.conditionLock lockWhenCondition:3];
    
    NSLog(@"__three");
    
    [self.conditionLock unlock];
}

执行结果:

2018-11-08 09:58:50.013405+0800 09-线程[2114:72695] __one
2018-11-08 09:58:51.017919+0800 09-线程[2114:72696] __two
2018-11-08 09:58:52.023380+0800 09-线程[2114:72697] __three

会依次执行onetwothree,Condition的默认条件是0

Atomic

atomic (原子性),在属性赋值的时候系统内部会封装一层spinlock进行加锁解锁操作
nonatomic (非原子性),直接赋值

dispatch_barrier_sync

线程安全中,其实只要保证单写多读就可以,用dispatch_barrier_sync就可以实现,在dispatch_barrier_sync执行写的操作,如图


注: 此函数需要在创建的并行队列执行

你可能感兴趣的:(iOS底层day9 - 多线程)