iOS NSOperation

前言

本文参考:行走的少年郎Shawn_Wang

就是想放张图.jpg

1. NSOperation、NSOperationQueue 简介

NSOperation、NSOperationQueue 是苹果提供给我们的一套多线程解决方案。是基于 GCD 更高一层的封装,完全面向对象。但是比 GCD 更简单易用、代码可读性也更高。

1.1 在什么情况下使用NSOperation和GCD

1、NSOperation是对GCD的封装,在异步操作之间的事务性,顺序行,依赖关系等方面表现性更强,适合较为复杂的需求。
2、GCD是C语言的底层API,执行效率较高,但是只支持FIFO队列。不可以重新设置优先级。适用于简单多线程任务。

1.2 NSOperation

NSOperation是系统提供的抽象基类,用于封装操作,类似于GCD中的Block内容。我们使用它的时候需要使用它的子类,有三种实现方式。

  • NSInvocationOperation (系统提供)
  • NSBlockOperation (系统提供)
  • 自定义子类

默认情况下,NSOperation单独使用时,系统同步执行操作。配合NSOperationQueue可以更好实现异步执行。

1.3 NSOperationQueue

NSOperationQueue为操作队列,也可称之为执行队列。可以自动实现多核并发运算,自动管理线程的生命周期。其底层也是使用线程池模型来管理。

  • NSOperation不同于GCD的调度队列FIFO(先进先出)的原则。它对于添加到队列中的操作,首先进入准备就绪的状态,然后进入就绪状态的操作开始执行。执行顺序由操作之间相对的优先级决定。可以通过maxConcurrentOperationCount最大并发数来控制并发、串行。
  • NSOperation为我们提供了两种不同类型的队列:主队列和自定义队列。主队列运行在主线程,自定义队列运行在后台。

2. NSOperation、NSOperationQueue 使用

2.1 创建操作 NSOperation

NSOperation用于封装操作,单独使用时,系统默认同步执行操作,一下演示三种创建方式

2.1.1 使用 NSInvocationOperation
- (void)NSInvocationOperation {
    NSOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task01) object:nil];
    [operation start];
}

- (void)task01 {
    for (int i = 0; i < 5; i++) {
        sleep(2);
        NSLog(@"NSInvocationOperation %d  当前线程:%@", i, [NSThread currentThread]);
    }
}
///执行结果
2018-10-26 16:10:46.975881+0800 NSOperation01[9175:185603] NSInvocationOperation 0  当前线程:<NSThread: 0x100503430>{number = 1, name = main}
2018-10-26 16:10:48.980178+0800 NSOperation01[9175:185603] NSInvocationOperation 1  当前线程:<NSThread: 0x100503430>{number = 1, name = main}
2018-10-26 16:10:50.984561+0800 NSOperation01[9175:185603] NSInvocationOperation 2  当前线程:<NSThread: 0x100503430>{number = 1, name = main}

从结果可以看到,在不配合NSOperationQueue使用的时候,操作是在当前线程下执行的,并没有开启新线程。
我们如果在子线程中调用NSInvocationOperation方法,可以看到:

[NSThread detachNewThreadSelector:@selector(NSInvocationOperation) toTarget:self withObject:nil];
///执行结果
2018-10-26 16:53:45.763838+0800 NSOperation01[9571:210775] NSInvocationOperation 0  当前线程:<NSThread: 0x6040004623c0>{number = 3, name = (null)}
2018-10-26 16:53:46.768404+0800 NSOperation01[9571:210775] NSInvocationOperation 1  当前线程:<NSThread: 0x6040004623c0>{number = 3, name = (null)}
2018-10-26 16:53:47.769358+0800 NSOperation01[9571:210775] NSInvocationOperation 2  当前线程:<NSThread: 0x6040004623c0>{number = 3, name = (null)}

总结,在其他线程单独使用NSInvocationOperation,操作在当前线程执行。

2.1.2 使用 NSBlockOperation

NSBlockOperation在主线程中调用

- (void)NSBlockOperation {
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 3; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"NSInvocationOperation %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    [operation start];
}
///执行结果:
2018-10-26 16:55:50.811943+0800 NSOperation01[9595:212531] NSBlockOperation 0  当前线程:<NSThread: 0x600000067000>{number = 1, name = main}
2018-10-26 16:55:51.813324+0800 NSOperation01[9595:212531] NSBlockOperation 1  当前线程:<NSThread: 0x600000067000>{number = 1, name = main}
2018-10-26 16:55:52.814693+0800 NSOperation01[9595:212531] NSBlockOperation 2  当前线程:<NSThread: 0x600000067000>{number = 1, name = main}

在子线程调用

[NSThread detachNewThreadSelector:@selector(NSBlockOperation) toTarget:self withObject:nil];
///执行结果:
2018-10-26 16:59:30.361025+0800 NSOperation01[9619:214602] NSBlockOperation 0  当前线程:<NSThread: 0x60000027d700>{number = 3, name = (null)}
2018-10-26 16:59:31.361746+0800 NSOperation01[9619:214602] NSBlockOperation 1  当前线程:<NSThread: 0x60000027d700>{number = 3, name = (null)}
2018-10-26 16:59:32.366639+0800 NSOperation01[9619:214602] NSBlockOperation 2  当前线程:<NSThread: 0x60000027d700>{number = 3, name = (null)}

调用结果
可以看到,和NSInvocationOperation一样,NSBlockOperation在没有配合NSOperationQueue的情况下使用,操作也是在当前线程执行。
但是 NSBlockOperation还提供了一个 addExecutionBlock: 方法,为 NSBlockOperation 添加额外的操作。这些操作(包括 blockOperationWithBlock 中的操作)可以在不同的线程中同时(并发)执行。只有当所有相关的操作已经完成执行时,才视为完成。

如果添加的操作多的话,blockOperationWithBlock: 中的操作也可能会在其他线程(非当前线程)中执行,这是由系统决定的,并不是说添加到 blockOperationWithBlock: 中的操作一定会在当前线程中执行。演示如下:

- (void)NSBlockOperation {
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"NSBlockOperation 01 %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    
    [operation addExecutionBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"NSBlockOperation 02 %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    
    [operation addExecutionBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"NSBlockOperation 03 %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    
    [operation addExecutionBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"NSBlockOperation 04 %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    
    [operation addExecutionBlock:^{
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:1];
            NSLog(@"NSBlockOperation 05 %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    [operation start];
}

调用结果

2018-10-26 17:17:08.198793+0800 NSOperation01[9666:222405] NSBlockOperation 02 0  当前线程:<NSThread: 0x600000468500>{number = 4, name = (null)}
2018-10-26 17:17:08.198793+0800 NSOperation01[9666:222443] NSBlockOperation 03 0  当前线程:<NSThread: 0x6000004685c0>{number = 5, name = (null)}
2018-10-26 17:17:08.198793+0800 NSOperation01[9666:222298] NSBlockOperation 01 0  当前线程:<NSThread: 0x60400007ed00>{number = 1, name = main}
2018-10-26 17:17:08.198793+0800 NSOperation01[9666:222403] NSBlockOperation 04 0  当前线程:<NSThread: 0x604000463240>{number = 3, name = (null)}
2018-10-26 17:17:09.199665+0800 NSOperation01[9666:222443] NSBlockOperation 03 1  当前线程:<NSThread: 0x6000004685c0>{number = 5, name = (null)}
2018-10-26 17:17:09.199665+0800 NSOperation01[9666:222405] NSBlockOperation 02 1  当前线程:<NSThread: 0x600000468500>{number = 4, name = (null)}
2018-10-26 17:17:09.199665+0800 NSOperation01[9666:222403] NSBlockOperation 04 1  当前线程:<NSThread: 0x604000463240>{number = 3, name = (null)}
2018-10-26 17:17:09.199665+0800 NSOperation01[9666:222298] NSBlockOperation 01 1  当前线程:<NSThread: 0x60400007ed00>{number = 1, name = main}
2018-10-26 17:17:10.201054+0800 NSOperation01[9666:222443] NSBlockOperation 05 0  当前线程:<NSThread: 0x6000004685c0>{number = 5, name = (null)}
2018-10-26 17:17:11.201436+0800 NSOperation01[9666:222443] NSBlockOperation 05 1  当前线程:<NSThread: 0x6000004685c0>{number = 5, name = (null)}

从上面的结果可以看出,各个操作是在不同的线程中异步执行的,也就是说,NSBlockOperation在不配合使用NSOperationQueue的时候,并不一定是在当前线程执行任务。

注意:(blockOperationWithBlock和addExecutionBlock,在我测试下,一个在主线程下执行,一个在子线程执行。但是有的大神说blockOperationWithBlock也有可能在子线程执行。这个暂时不确定)

2.1.3 自定义继承自NSOperation的子类

自定义NSOperation,执行串行任务

- (void)main {
    @try {
        ///提供一个标识变量,来表示需要执行的操作是否完成了。没有开始之前为false
        BOOL taskIsFinished = false;
        ///while循环,保证只有当没有执行完成和没有被取消,才执行自定义操作
        while (!taskIsFinished && ![self isCancelled]) {
            sleep(2);
            NSLog(@"%@",[NSThread currentThread]);
            taskIsFinished = true;
        }
    }
    @catch (NSException *result) {
        NSLog(@"error....%@",result);
    }
    NSLog(@"end .....");
}

调用方法如下:

    SerialOperation *op = [[SerialOperation alloc] init];
    [op start];

运行结果

2018-10-27 16:46:54.359306+0800 NSOperation01[18903:274802] <NSThread: 0x60000007bb80>{number = 1, name = main}
2018-10-27 16:46:54.359525+0800 NSOperation01[18903:274802] end .....

自定义串行操作,仅仅需要自定义main方法,将需要执行的操作写在main方法中。至于是否需要自定义start方法,可根据自己的实际需要。

自定义NSOperation,执行并行任务
自定义并行任务,需要自定义以下几个方法

  • star:所有并行的 Operations 都必须重写这个方法,然后在你想要执行的线程中手动调用这个方法。注意:任何时候都不能调用父类的start方法。
  • main:该方法可选,如果你在start方法中定义了你的任务,则这个方法就可以不实现,但通常为了代码逻辑清晰,通常会在该方法中定义自己的任务
  • isExecuting: 是否执行中(必须实现),需要实现KVO通知机制。
  • isFinished: 是否已完成(必须实现),需要实现KVO通知机制。
  • isConcurrent: (忽略)该方法现在已经由isAsynchronous方法代替,并且 NSOperationQueue 也已经忽略这个方法的值。
  • isAsynchronous: 该方法默认返回 NO ,表示非并发执行(必须实现)。并发执行需要自定义并且返回 YES。后面会根据这个返回值来决定是否并发。
@interface ConcurrenceOperation () {
    BOOL executing;     ///执行中
    BOOL finished;      ///已完成
}
@end

@implementation ConcurrenceOperation

- (instancetype)init {
    if (self = [super init]) {
        executing = false;
        finished = false;
    }
    return self;
}

- (void)main {
    NSLog(@"main begin");
    @try {
        ///必须为自定义的operation提供autoreleasePool,因为operation完成需要销毁
        @autoreleasepool {
            ///记录需要执行的操作是否完成了,没有完成之前为false
            BOOL taskIsFinished = false;
            ///while:只有没有执行完成和没有被取消的时候,才执行自定义的操作
            while (!taskIsFinished && ![self isCancelled]) {
                
                sleep(2);
                NSLog(@"%@",[NSThread currentThread]);
                
                ///相应的操作都已经完成,后面就是要通知KVO,我们的操作完成了
                taskIsFinished = true;
            }
            
            ///通过KVO,更改属性为操作完成
            [self completeOperation];
            
        }
    } @catch (NSException *exception) {
        NSLog(@"自定义operation异常: %@",exception);
    }
    NSLog(@"main end");
}

///所有并行的 Operations 都必须重写这个方法,然后在你想要执行的线程中手动调用这个方法。注意:任何时候都不能调用父类的start方法。
- (void)start {
    if ([self isCancelled]) {
        [self willChangeValueForKey:@"isFinished"];
        finished = true;
        [self willChangeValueForKey:@"isFinished"];
        return;
    }
    
    [self willChangeValueForKey:@"isExecuting"];
    [NSThread detachNewThreadSelector:@selector(main) toTarget:self withObject:nil];
    executing = true;
    [self didChangeValueForKey:@"isExecuting"];
}

- (void)startOperation {
    ///自身已经转备好,并且没有被取消
    if ([self isReady] && ![self isCancelled]) {
        if (![self isAsynchronous]) {
            [self start];
        
        } else {
            [NSThread detachNewThreadSelector:@selector(start) toTarget:self withObject:nil];
        }
    
    } else if ([self isCancelled]) {
        [self completeOperation];
    }
}

- (void)completeOperation {
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];
    
    executing = false;
    finished = true;
    
    [self didChangeValueForKey:@"isFinished"];
    [self didChangeValueForKey:@"isExecuting"];
}

///是否已完成,需要实现KVO通知机制
- (BOOL)isFinished {
    return finished;
}

///是否执行中,需要实现KVO通知机制
- (BOOL)isExecuting {
    return executing;
}

///该方法默认返回 NO ,表示非并发执行,并发执行需要自定义并且返回 YES。后面会根据这个返回值来决定是否并发。
- (BOOL)isAsynchronous {
    return true;
}

调用方法

ConcurrenceOperation *op = [[ConcurrenceOperation alloc] init];
NSLog(@"operation start");
[op startOperation];
NSLog(@"operation end");

执行结果

2018-10-31 16:32:55.087711+0800 NSOperation01[800:25423] operation start
2018-10-31 16:32:55.087938+0800 NSOperation01[800:25423] operation end
2018-10-31 16:32:55.088822+0800 NSOperation01[800:25495] main begin
2018-10-31 16:32:57.090471+0800 NSOperation01[800:25495] <NSThread: 0x604000463c00>{number = 4, name = (null)}
2018-10-31 16:32:57.090759+0800 NSOperation01[800:25495] main end
2.2 创建 NSOperationQueue

NSOperationQueue创建队列一共有两种方式:主队列和自定义队列

  • 主队列:在主线程执行(使用 addExecutionBlock方法除外)
    ///获取主队列
    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
  • 自定义队列:包括串行和并行。在子线程执行
    ///自定义队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
2.3 将操作加入到队列中

将NSOperation加入到NSOperationQueue中,一共有两种方法

  - (void)addOperation:(NSOperation *)op;
  - (void)addOperationWithBlock:(void (^)(void))block;
  1. -(void)addOperation:(NSOperation *)op; 使用
- (void)operation {
    ///NSInvocationOperation
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil];
    ///NSBlockOperation
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"2-- %d  当前线程:%@  NSBlockOperation", i, [NSThread currentThread]);
        }
    }];
    ///自定义NSOperation
    SerialOperation *op3 = [[SerialOperation alloc] init];

    ///自定义队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
    
}

- (void)task {
    for (int i = 0; i < 2; i++) {
        sleep(2);
        NSLog(@"1-- %d  当前线程:%@  NSInvocationOperation", i, [NSThread currentThread]);
    }
}

运行结果:

2018-11-01 17:34:59.427986+0800 NSOperation01[2938:176727] 2-- 0  当前线程:<NSThread: 0x600000267080>{number = 3, name = (null)}  自定义NSOperation
2018-11-01 17:34:59.427986+0800 NSOperation01[2938:176725] 2-- 0  当前线程:<NSThread: 0x604000475c40>{number = 4, name = (null)}  NSBlockOperation
2018-11-01 17:34:59.427997+0800 NSOperation01[2938:176724] 1-- 0  当前线程:<NSThread: 0x600000273980>{number = 5, name = (null)}  NSInvocationOperation
2018-11-01 17:35:01.431141+0800 NSOperation01[2938:176727] 2-- 1  当前线程:<NSThread: 0x600000267080>{number = 3, name = (null)}  自定义NSOperation
2018-11-01 17:35:01.431141+0800 NSOperation01[2938:176724] 1-- 1  当前线程:<NSThread: 0x600000273980>{number = 5, name = (null)}  NSInvocationOperation
2018-11-01 17:35:01.431161+0800 NSOperation01[2938:176725] 2-- 1  当前线程:<NSThread: 0x604000475c40>{number = 4, name = (null)}  NSBlockOperation

从运行结果可以看出,向NSOperationQueue添加任务,默认并行。所有操作都在子线程中执行。

  1. -(void)addOperationWithBlock:(void (^)(void))block;使用
- (void)addOperationToOperationQueueByBlockMethod {
    ///自定义队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"1-- %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    [queue addOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"2-- %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    [queue addOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"3-- %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
}

运行结果

2018-11-01 17:42:06.959063+0800 NSOperation01[2962:180324] 2-- 0  当前线程:<NSThread: 0x60000027de40>{number = 5, name = (null)}
2018-11-01 17:42:06.959063+0800 NSOperation01[2962:180325] 1-- 0  当前线程:<NSThread: 0x60000027d280>{number = 3, name = (null)}
2018-11-01 17:42:06.959063+0800 NSOperation01[2962:180322] 3-- 0  当前线程:<NSThread: 0x60400007efc0>{number = 4, name = (null)}
2018-11-01 17:42:08.961127+0800 NSOperation01[2962:180325] 1-- 1  当前线程:<NSThread: 0x60000027d280>{number = 3, name = (null)}
2018-11-01 17:42:08.961127+0800 NSOperation01[2962:180324] 2-- 1  当前线程:<NSThread: 0x60000027de40>{number = 5, name = (null)}
2018-11-01 17:42:08.961127+0800 NSOperation01[2962:180322] 3-- 1  当前线程:<NSThread: 0x60400007efc0>{number = 4, name = (null)}

从运行结果可以看出,使用addOperationWithBlock添加任务,默认并行。所有操作都在子线程中执行。

3. 控制并行和串行任务(maxConcurrentOperationCount)

maxConcurrentOperationCount为最大并发数,可以通过它控制任务是并行还是串行。该值默认为-1,表示不做限制。当设置为1时,队列为串行队列。当大于1时,队列为并发队列。当该值超过最大限制时,系统会自动调整为系统默认的最大值。(如何设置为0,表示不会执行任务)

- (void)addOperationToOperationQueueByBlockMethod {
    ///自定义队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    queue.maxConcurrentOperationCount = 1;   ///串行
//    queue.maxConcurrentOperationCount = 3; ///并发队列
    
    [queue addOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"1-- %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    [queue addOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"2-- %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
    [queue addOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"3-- %d  当前线程:%@", i, [NSThread currentThread]);
        }
    }];
}

最大并发数量maxConcurrentOperationCount为1时,执行结果:

2018-11-01 18:02:10.474909+0800 NSOperation01[3017:189591] 1-- 0  当前线程:<NSThread: 0x60400026e6c0>{number = 3, name = (null)}
2018-11-01 18:02:12.478708+0800 NSOperation01[3017:189591] 1-- 1  当前线程:<NSThread: 0x60400026e6c0>{number = 3, name = (null)}
2018-11-01 18:02:14.481762+0800 NSOperation01[3017:189593] 2-- 0  当前线程:<NSThread: 0x60400026e800>{number = 4, name = (null)}
2018-11-01 18:02:16.486238+0800 NSOperation01[3017:189593] 2-- 1  当前线程:<NSThread: 0x60400026e800>{number = 4, name = (null)}
2018-11-01 18:02:18.491204+0800 NSOperation01[3017:189591] 3-- 0  当前线程:<NSThread: 0x60400026e6c0>{number = 3, name = (null)}
2018-11-01 18:02:20.493978+0800 NSOperation01[3017:189591] 3-- 1  当前线程:<NSThread: 0x60400026e6c0>{number = 3, name = (null)}

最大并发数量maxConcurrentOperationCount为3时,执行结果:

2018-11-01 18:12:21.138678+0800 NSOperation01[3052:194817] 2-- 0  当前线程:<NSThread: 0x600000278300>{number = 3, name = (null)}
2018-11-01 18:12:21.138680+0800 NSOperation01[3052:194815] 3-- 0  当前线程:<NSThread: 0x60400046c7c0>{number = 4, name = (null)}
2018-11-01 18:12:21.138680+0800 NSOperation01[3052:194816] 1-- 0  当前线程:<NSThread: 0x600000278480>{number = 5, name = (null)}
2018-11-01 18:12:23.140932+0800 NSOperation01[3052:194816] 1-- 1  当前线程:<NSThread: 0x600000278480>{number = 5, name = (null)}
2018-11-01 18:12:23.140933+0800 NSOperation01[3052:194815] 3-- 1  当前线程:<NSThread: 0x60400046c7c0>{number = 4, name = (null)}
2018-11-01 18:12:23.141296+0800 NSOperation01[3052:194817] 2-- 1  当前线程:<NSThread: 0x600000278300>{number = 3, name = (null)}

以上执行结果证明,当最大并发数maxConcurrentOperationCount为1时,队列串行执行,大于1时,并发执行。

4. NSOperation操作依赖

NSOperation、NSOperationQueue 最吸引人的地方是它能添加操作之间的依赖关系。通过添加操作依赖,我们能很方便的控制操作之前的执行顺序。NSOperation 提供了3个接口供我们管理和查看依赖。

- (void)addDependency:(NSOperation *)op; 添加依赖,使当前操作依赖于操作 op 的完成。
- (void)removeDependency:(NSOperation *)op; 移除依赖,取消当前操作对操作 op 的依赖。
@property (readonly, copy) NSArray<NSOperation *> *dependencies; 在当前操作开始执行之前完成执行的所有操作对象数组。

代码示例如下:op3 依赖 op2, op2 依赖op1;

- (void)operation {
    ///NSInvocationOperation
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil];
    ///NSBlockOperation
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"2-- %d  当前线程:%@  NSBlockOperation", i, [NSThread currentThread]);
        }
    }];
    ///自定义NSOperation
    SerialOperation *op3 = [[SerialOperation alloc] init];

    ///自定义队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    ///添加依赖关系
    [op3 addDependency:op2];
    [op2 addDependency:op1];
    
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
}

执行结果如下:

2018-11-01 18:21:32.820190+0800 NSOperation01[3091:199720] 1-- 0  当前线程:<NSThread: 0x600000261680>{number = 3, name = (null)}  NSInvocationOperation
2018-11-01 18:21:34.820641+0800 NSOperation01[3091:199720] 1-- 1  当前线程:<NSThread: 0x600000261680>{number = 3, name = (null)}  NSInvocationOperation
2018-11-01 18:21:36.821443+0800 NSOperation01[3091:199721] 2-- 0  当前线程:<NSThread: 0x600000261f40>{number = 4, name = (null)}  NSBlockOperation
2018-11-01 18:21:38.822606+0800 NSOperation01[3091:199721] 2-- 1  当前线程:<NSThread: 0x600000261f40>{number = 4, name = (null)}  NSBlockOperation
2018-11-01 18:21:40.827625+0800 NSOperation01[3091:199721] 3-- 0  当前线程:<NSThread: 0x600000261f40>{number = 4, name = (null)}  自定义NSOperation
2018-11-01 18:21:42.828893+0800 NSOperation01[3091:199721] 3-- 1  当前线程:<NSThread: 0x600000261f40>{number = 4, name = (null)}  自定义NSOperation

虽然线程是并发执行,但是因为op3 依赖 op2, op2 依赖op1,所以该队列最终串行执行。

5. NSOperation 优先级

在IOS8,这个属性已经被苹果框架系统性的忽略了,threadPriority已由NSQualityOfService属性替代.

NSOperation提供了一个queuePriority(优先级)属性,它适用于同一队列中的操作,默认情况下,所有新创建的操作对象优先级都是NSOperationQueuePriorityNormal,我们可以通过setQueuePriority:方法来改变当前操作在同一队列中的执行优先级。

// 优先级的取值
typedef NS_ENUM(NSInteger, NSOperationQueuePriority) {
    NSOperationQueuePriorityVeryLow = -8L,
    NSOperationQueuePriorityLow = -4L,
    NSOperationQueuePriorityNormal = 0,
    NSOperationQueuePriorityHigh = 4,
    NSOperationQueuePriorityVeryHigh = 8
};

对于添加到队列中的操作,首先进入准备就绪的状态(就绪状态取决于操作之间的依赖关系),然后进入就绪状态的操作的开始执行顺序(非结束执行顺序)由操作之间相对的优先级决定(优先级是操作对象自身的属性)。

注意:优先级不能替代依赖关系,如果一个队列中既包含高优先级操作,又包含低优先级操作,并且两个操作都已经准备就绪,那么队列先执行高优先级操作。如果,一个队列中既包含了准备就绪状态的操作,又包含了未准备就绪的操作,未准备就绪的操作优先级比准备就绪的操作优先级高。那么,虽然准备就绪的操作优先级低,也会优先执行。优先级不能取代依赖关系。如果要控制操作间的启动顺序,则必须使用依赖关系。
我们也可以这么理解,优先级作用于已经准备就绪的操作,而操作之间的依赖作用于准备就绪状态之前,依赖决定谁先进入准备就绪状态。

6. NSOperation 服务质量 Quality of Service

Queality of Service 是 iOS8 &OS X Yosemite出现的一个新的概念,它为调度系统创造一致的高层语义。对于NSOperation来说,为了支持这一新的qualityOfService属性,threadProperty这一属性便废弃了。服务级别根据CPU,网络和磁盘的分配来创建一个操作的系统优先级。一个高质量的服务就意味着更多的资源得以提供来更快的完成操作。

typedef NS_ENUM(NSInteger, NSQualityOfService) {
    NSQualityOfServiceUserInteractive = 0x21,
    NSQualityOfServiceUserInitated = 0x19,
    NSQualityOfServiceUtility = 0x11,
    NSQualityOfServiceBackground = 0x09,
    NSQualityOfServiceDefault = -1
} NS_ENUM_AVAILABLE(10_10, 8_0);
  • UserInteractive: QoS 用于直接参与提供一个交互式UI,如处理事件或对屏幕的绘制。
  • UserInitiated: QoS用于表示执行工作已经被用户显示提出并且要求结果能够立即展示以便进行进一步的用户交互。比如:用户在信息列表点击之后立即加载一个email。
  • Utility: QoS用于表述执行一项工作后,用户并不需要立即得到结果。这一工作通常用户已经请求过或者在初始化的时候已经自动执行,不会阻碍用户用户的进一步交互,通常在用户可见的时间尺度和可能由一个非模态的进度指示器展示给用户。
  • Background: QoS用于那些非用户初始化或可见的工作。通常说来,用户甚至不知道这想工作已经发生,但是它会以最有效的方法运行那些高优先级的QoS。例如:内容抓取,搜索索引,备份,同步与外部系统的数据。
  • Default:默认的QoS表明QoS信息缺失。尽可能的从其它资源推断可能的QoS信息。如果这一推断不成立,一个位于UserInitiated和Utility之间的QoS将得以使用。
    程序测试如下:
- (void)operation {
    ///NSInvocationOperation
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task) object:nil];
    ///NSBlockOperation
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        for (int i = 0; i < 2; i++) {
            sleep(2);
            NSLog(@"2-- %d  当前线程:%@  NSBlockOperation", i, [NSThread currentThread]);
        }
    }];
    ///自定义NSOperation
    SerialOperation *op3 = [[SerialOperation alloc] init];
    
    ///自定义队列
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        
    op3.qualityOfService = NSQualityOfServiceUserInteractive;
    
    [queue addOperation:op1];
    [queue addOperation:op2];
    [queue addOperation:op3];
}

打印结果:

2018-11-02 09:19:16.185067+0800 NSOperation01[996:30955] 3-- 0  当前线程:<NSThread: 0x6000002761c0>{number = 3, name = (null)}  自定义NSOperation
2018-11-02 09:19:16.188521+0800 NSOperation01[996:30953] 1-- 0  当前线程:<NSThread: 0x604000271700>{number = 4, name = (null)}  NSInvocationOperation
2018-11-02 09:19:16.188521+0800 NSOperation01[996:30952] 2-- 0  当前线程:<NSThread: 0x60000027f5c0>{number = 5, name = (null)}  NSBlockOperation
2018-11-02 09:19:18.186568+0800 NSOperation01[996:30955] 3-- 1  当前线程:<NSThread: 0x6000002761c0>{number = 3, name = (null)}  自定义NSOperation
2018-11-02 09:19:18.189809+0800 NSOperation01[996:30953] 1-- 1  当前线程:<NSThread: 0x604000271700>{number = 4, name = (null)}  NSInvocationOperation
2018-11-02 09:19:18.189809+0800 NSOperation01[996:30952] 2-- 1  当前线程:<NSThread: 0x60000027f5c0>{number = 5, name = (null)}  NSBlockOperation

7.NSOperation、NSOperationQueue 线程间的通信

在 iOS 开发过程中,我们一般在主线程里边进行 UI 刷新,例如:点击、滚动、拖拽等事件。我们通常把一些耗时的操作放在其他线程,比如说图片下载、文件上传等耗时操作。而当我们有时候在其他线程完成了耗时操作时,需要回到主线程,那么就用到了线程之间的通讯。

- (void)communication {
    // 1.创建队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    
    // 2.添加操作
    [queue addOperationWithBlock:^{
        // 异步进行耗时操作
        for (int i = 0; i < 2; i++) {
            [NSThread sleepForTimeInterval:2]; // 模拟耗时操作
            NSLog(@"1---%@", [NSThread currentThread]); // 打印当前线程
        }
        
        // 回到主线程
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            // 进行一些 UI 刷新等操作
            for (int i = 0; i < 2; i++) {
                [NSThread sleepForTimeInterval:2]; // 模拟耗时操作
                NSLog(@"2---%@", [NSThread currentThread]); // 打印当前线程
            }
        }];
    }];
}

打印结果:

2018-11-02 09:34:28.628782+0800 NSOperation01[1063:38980] 1---<NSThread: 0x60000046ee80>{number = 3, name = (null)}
2018-11-02 09:34:30.634337+0800 NSOperation01[1063:38980] 1---<NSThread: 0x60000046ee80>{number = 3, name = (null)}
2018-11-02 09:34:32.636039+0800 NSOperation01[1063:38879] 2---<NSThread: 0x60000007d0c0>{number = 1, name = main}
2018-11-02 09:34:34.637110+0800 NSOperation01[1063:38879] 2---<NSThread: 0x60000007d0c0>{number = 1, name = main}

8. NSOperation、NSOperationQueue 线程同步和线程安全

  • 线程安全:如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。
    若每个线程中对全局变量、静态变量只有读操作,而无写操作,一般来说,这个全局变量是线程安全的;若有多个线程同时执行写操作(更改变量),一般都需要考虑线程同步,否则的话就可能影响线程安全。
  • 线程同步:可理解为线程 A 和 线程 B 一块配合,A 执行到一定程度时要依靠线程 B 的某个结果,于是停下来,示意 B 运行;B 依言执行,再将结果给 A;A 再继续操作。

举个简单例子就是:两个人在一起聊天。两个人不能同时说话,避免听不清(操作冲突)。等一个人说完(一个线程结束操作),另一个再说(另一个线程再开始操作)。

下面,我们模拟火车票售卖的方式,实现 NSOperation 线程安全和解决线程同步问题。
场景:总共有50张火车票,有两个售卖火车票的窗口,一个是北京火车票售卖窗口,另一个是上海火车票售卖窗口。两个窗口同时售卖火车票,卖完为止。

8.1 NSOperation、NSOperationQueue 非线程安全
- (void)initTicketStatusNotSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程
    
    self.ticketSurplusCount = 10;
    
    // 1.创建 queue1,queue1 代表北京火车票售卖窗口
    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
    queue1.maxConcurrentOperationCount = 1;
    
    // 2.创建 queue2,queue2 代表上海火车票售卖窗口
    NSOperationQueue *queue2 = [[NSOperationQueue alloc] init];
    queue2.maxConcurrentOperationCount = 1;
    
    // 3.创建卖票操作 op1
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        [self saleTicketNotSafe];
    }];
    
    // 4.创建卖票操作 op2
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        [self saleTicketNotSafe];
    }];
    
    // 5.添加操作,开始卖票
    [queue1 addOperation:op1];
    [queue2 addOperation:op2];
}

/**
 * 售卖火车票(非线程安全)
 */
- (void)saleTicketNotSafe {
    while (1) {
        
        if (self.ticketSurplusCount > 0) {
            //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        } else {
            NSLog(@"所有火车票均已售完");
            break;
        }
    }
}

测试结果:

2018-11-02 09:40:47.440150+0800 NSOperation01[1091:42131] currentThread---<NSThread: 0x604000261240>{number = 1, name = main}
2018-11-02 09:40:47.440822+0800 NSOperation01[1091:42212] 剩余票数:9 窗口:<NSThread: 0x600000464300>{number = 3, name = (null)}
2018-11-02 09:40:47.440827+0800 NSOperation01[1091:42221] 剩余票数:8 窗口:<NSThread: 0x60400046bb80>{number = 4, name = (null)}
2018-11-02 09:40:47.646226+0800 NSOperation01[1091:42221] 剩余票数:7 窗口:<NSThread: 0x60400046bb80>{number = 4, name = (null)}
2018-11-02 09:40:47.646229+0800 NSOperation01[1091:42212] 剩余票数:7 窗口:<NSThread: 0x600000464300>{number = 3, name = (null)}
2018-11-02 09:40:47.847408+0800 NSOperation01[1091:42221] 剩余票数:6 窗口:<NSThread: 0x60400046bb80>{number = 4, name = (null)}
2018-11-02 09:40:47.847419+0800 NSOperation01[1091:42212] 剩余票数:5 窗口:<NSThread: 0x600000464300>{number = 3, name = (null)}
2018-11-02 09:40:48.049470+0800 NSOperation01[1091:42221] 剩余票数:4 窗口:<NSThread: 0x60400046bb80>{number = 4, name = (null)}
2018-11-02 09:40:48.049470+0800 NSOperation01[1091:42212] 剩余票数:3 窗口:<NSThread: 0x600000464300>{number = 3, name = (null)}
2018-11-02 09:40:48.250105+0800 NSOperation01[1091:42212] 剩余票数:2 窗口:<NSThread: 0x600000464300>{number = 3, name = (null)}
2018-11-02 09:40:48.250105+0800 NSOperation01[1091:42221] 剩余票数:1 窗口:<NSThread: 0x60400046bb80>{number = 4, name = (null)}
2018-11-02 09:40:48.450959+0800 NSOperation01[1091:42221] 所有火车票均已售完
2018-11-02 09:40:48.450964+0800 NSOperation01[1091:42212] 剩余票数:0 窗口:<NSThread: 0x600000464300>{number = 3, name = (null)}
2018-11-02 09:40:48.654515+0800 NSOperation01[1091:42212] 所有火车票均已售完

通过结果可以看到,在不考虑线程安全的前提下,多个线程访问同一个数据,会造成数据混乱。不符合我们售卖火车票的需求。

8.2 NSOperation、NSOperationQueue 线程安全

线程安全解决方案:可以给线程加锁,在一个线程执行该操作的时候,不允许其他线程进行操作。iOS 实现线程加锁有很多种方式。@synchronized、 NSLock、NSRecursiveLock、NSCondition、NSConditionLock、pthread_mutex、dispatch_semaphore、OSSpinLock、atomic(property) set/ge等等各种方式。这里我们使用 NSLock 对象来解决线程同步问题。NSLock 对象可以通过进入锁时调用 lock 方法,解锁时调用 unlock 方法来保证线程安全。

- (void)initTicketStatusNotSave {
    NSLog(@"currentThread---%@",[NSThread currentThread]); // 打印当前线程
    
    self.ticketSurplusCount = 10;
    
    // 1.创建 queue1,queue1 代表北京火车票售卖窗口
    NSOperationQueue *queue1 = [[NSOperationQueue alloc] init];
    queue1.maxConcurrentOperationCount = 1;
    
    // 2.创建 queue2,queue2 代表上海火车票售卖窗口
    NSOperationQueue *queue2 = [[NSOperationQueue alloc] init];
    queue2.maxConcurrentOperationCount = 1;
    
    // 3.创建卖票操作 op1
    NSBlockOperation *op1 = [NSBlockOperation blockOperationWithBlock:^{
        [self saleTicketNotSafe];
    }];
    
    // 4.创建卖票操作 op2
    NSBlockOperation *op2 = [NSBlockOperation blockOperationWithBlock:^{
        [self saleTicketNotSafe];
    }];
    
    // 5.添加操作,开始卖票
    [queue1 addOperation:op1];
    [queue2 addOperation:op2];
}

/**
 * 售卖火车票(非线程安全)
 */
- (void)saleTicketNotSafe {
    while (1) {
        [self.lock lock];
        if (self.ticketSurplusCount > 0) {
            //如果还有票,继续售卖
            self.ticketSurplusCount--;
            NSLog(@"%@", [NSString stringWithFormat:@"剩余票数:%d 窗口:%@", self.ticketSurplusCount, [NSThread currentThread]]);
            [NSThread sleepForTimeInterval:0.2];
        }
        [self.lock unlock];
        if (self.ticketSurplusCount <= 0) {
            NSLog(@"所有火车票均已售完");
            break;
        }
    }
}

测试结果如下:

2018-11-02 09:48:59.531168+0800 NSOperation01[1154:47192] currentThread---<NSThread: 0x604000073940>{number = 1, name = main}
2018-11-02 09:48:59.531912+0800 NSOperation01[1154:47271] 剩余票数:9 窗口:<NSThread: 0x600000266140>{number = 4, name = (null)}
2018-11-02 09:48:59.531935+0800 NSOperation01[1154:47264] 剩余票数:8 窗口:<NSThread: 0x604000469c40>{number = 3, name = (null)}
2018-11-02 09:48:59.737239+0800 NSOperation01[1154:47264] 剩余票数:7 窗口:<NSThread: 0x604000469c40>{number = 3, name = (null)}
2018-11-02 09:48:59.737239+0800 NSOperation01[1154:47271] 剩余票数:6 窗口:<NSThread: 0x600000266140>{number = 4, name = (null)}
2018-11-02 09:48:59.941367+0800 NSOperation01[1154:47271] 剩余票数:5 窗口:<NSThread: 0x600000266140>{number = 4, name = (null)}
2018-11-02 09:48:59.941396+0800 NSOperation01[1154:47264] 剩余票数:5 窗口:<NSThread: 0x604000469c40>{number = 3, name = (null)}
2018-11-02 09:49:00.145074+0800 NSOperation01[1154:47271] 剩余票数:3 窗口:<NSThread: 0x600000266140>{number = 4, name = (null)}
2018-11-02 09:49:00.145074+0800 NSOperation01[1154:47264] 剩余票数:4 窗口:<NSThread: 0x604000469c40>{number = 3, name = (null)}
2018-11-02 09:49:00.346596+0800 NSOperation01[1154:47271] 剩余票数:2 窗口:<NSThread: 0x600000266140>{number = 4, name = (null)}
2018-11-02 09:49:00.346596+0800 NSOperation01[1154:47264] 剩余票数:2 窗口:<NSThread: 0x604000469c40>{number = 3, name = (null)}
2018-11-02 09:49:00.547757+0800 NSOperation01[1154:47264] 剩余票数:1 窗口:<NSThread: 0x604000469c40>{number = 3, name = (null)}
2018-11-02 09:49:00.547775+0800 NSOperation01[1154:47271] 剩余票数:0 窗口:<NSThread: 0x600000266140>{number = 4, name = (null)}
2018-11-02 09:49:00.751857+0800 NSOperation01[1154:47271] 所有火车票均已售完
2018-11-02 09:49:00.751857+0800 NSOperation01[1154:47264] 所有火车票均已售完

通过打印的结果,我们可以看出,使用 NSLock 加锁,可以保证线程安全

NSLock的执行原理:

  • 线程 1 中的 lock 锁上了,所以线程 2 中的 lock 加锁失败,阻塞线程 2,但 2 s 后线程 1 中的 lock 解锁,线程 2 就立即加锁成功,执行线程 2 中的后续代码。
  • 查到的资料显示互斥锁会使得线程阻塞,阻塞的过程又分两个阶段,第一阶段是会先空转,可以理解成跑一个 while 循环,不断地去申请加锁,在空转一定时间之后,线程会进入 waiting 状态,此时线程就不占用CPU资源了,等锁可用的时候,这个线程会立即被唤醒。

9. NSOperationQueue 常用属性和方法

  • -(void)cancelAllOperations; 可以取消队列的所有操作(取消没有准备就绪的操作)。
  • -(BOOL)isSuspended; 判断队列是否处于暂停状态。 YES 为暂停状态,NO 为恢复状态。
  • -(void)setSuspended:(BOOL)b; 可设置操作的暂停和恢复,YES 代表暂停队列,NO 代表恢复队列。
    操作同步
  • -(void)waitUntilAllOperationsAreFinished; 阻塞当前线程,直到队列中的操作全部执行完毕。
    添加/获取操作`
  • -(void)addOperationWithBlock:(void (^)(void))block; 向队列中添加一个 NSBlockOperation 类型操作对象。
  • (void)addOperations:(NSArray *)ops waitUntilFinished:(BOOL)wait; 向队列中添加操作数组,wait 标志是否阻塞当前线程直到所有操作结束
  • -(NSArray *)operations; 当前在队列中的操作数组(某个操作执行结束后会自动从这个数组清除)。
  • -(NSUInteger)operationCount; 当前队列中的操作数。
    获取队列
  • -(id)currentQueue; 获取当前队列,如果当前线程不是在 NSOperationQueue 上运行则返回 nil。
  • -(id)mainQueue; 获取主队列。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,591评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,448评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,823评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,204评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,228评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,190评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,078评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,923评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,334评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,550评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,727评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,428评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,022评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,672评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,826评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,734评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,619评论 2 354

推荐阅读更多精彩内容