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);
            }
        };
    });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容