iOS多线程面试题:如何使用两个线程交替打印1--100?

使用两个线程交替打印奇偶数,需要用到锁来实现,下边有3种实现方式:

  • 使用NSLock实现
    NSLock *lock = [[NSLock alloc] init];
    __block int number = 0;
    dispatch_async(queue1, ^{
        while (number < 100) {
            [lock lock];
            if (number%2 == 0) {
                number++;
                NSLog(@"奇数---%d",number);
            }
            [lock unlock];
        };
    });
    
    dispatch_async(queue2, ^{
        while (number < 100) {
            [lock lock];
            if (number%2 != 0) {
                number++;
                NSLog(@"偶数---%d",number);
            }
            [lock unlock];
        };
    });
  • 使用NSCondition实现
NSCondition *cond = [[NSCondition alloc] init];
    __block int number = 0;
    dispatch_async(queue1, ^{
        while (number < 100) {
            [cond lock];
            if (number%2 != 0) {
                [cond signal];
                [cond wait];
            }
            number++;
            NSLog(@"queue1---%d",number);
            [cond unlock];
        };
    });

    dispatch_async(queue2, ^{
        while (number < 100) {
            [cond lock];
            if (number%2 == 0) {
                [cond signal];
                [cond wait];
            }
            number++;
            NSLog(@"queue2---%d",number);
            [cond unlock];
        };
    });
  • 使用dispatch_semaphore_t实现
    __block int number = 0;
    dispatch_async(queue1, ^{
        while (number < 100) {
            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
            number++;
            NSLog(@"奇数---%d",number);
            if (number%2 != 0) {
                dispatch_semaphore_signal(sema);
            }
        };
    });
    
    dispatch_async(queue2, ^{
        while (number < 100) {
            dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
            number++;
            NSLog(@"偶数---%d",number);
            if (number%2 == 0) {
                dispatch_semaphore_signal(sema);
            }
        };
    });

你可能感兴趣的:(iOS多线程面试题:如何使用两个线程交替打印1--100?)