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

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

作者: 银古 | 来源:发表于2021-11-08 17:25 被阅读0次

    使用两个线程交替打印奇偶数,需要用到锁来实现,下边有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?

          本文链接:https://www.haomeiwen.com/subject/iuauzltx.html