NSThread & NSOperation & GCD

NSThread:
1、NSThread属于轻量级的线程,类似其它平台传统的线程使用方式;使用者能明确的管理线程的生命周期以及运行方式;
2、在需要一个确定的线程使用场景较为常用,如需要某些操作一直运行在一个固定的线程(可用NSMachPortperformSelector:onThread:withObject:waitUntilDone:);
3、NSThread必须要自己维护一个runloop,保证线程不退出,如:
- (void)threadRunloop
{
    @autoreleasepool
    {
        while (![[NSThread currentThread] isCancelled])
        {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                     beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]];
        }
    }
}


NSOperation:
1、NSOperation其实是一个任务的封装,靠NSOperationQueue实现多线程;
2、NSOperation底层实现:在OS X v10.6(iOS 4)之前通过NSThread实现,OS X v10.6(iOS 4)之后通过GCD实现;(Operation queues usually provide the threads used to run their operations. In OS X v10.6 and later, operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as concurrent or non-concurrent operations. In OS X v10.5, however, operations are executed on separate threads only if their isConcurrent method returns NO. If that method returns YES, the operation object is expected to create its own thread (or start some asynchronous operation); the queue does not provide a thread for it.)
3、NSOperationQueue分为concurrent(由Operation自己实现多线程)和non-concurrent方式,OS X v10.6(iOS 4)之前NSOperationQueue根据isConcurrent判断是否给该Operation分配一个线程(YES不单独分配,NO单独分配一个线程),OS X v10.6(iOS 4)之后NSOperationQueue统一按照non-councurrent方式处理(如果使用Queue方式,苹果官NSOperation官方文档;
4、NSOperation可以监测线程运行的各种状态,并且可以cancel掉一个NSOperation包括正在运行的Operation(需要自己监测isCanceled实现线程退出),而GCD一旦创建就没办法控制和监控;
5、NSOperation被cancel之后,如果已经在运行态会尽可能快的终止任务移除队列,如果还没有在运行态OS X v10.6之后会尽可能快的调用该Operation然后终止任务移除队列,OS X v10.6之前则不会提高其优先级按照原来的顺序调用Operation.start然后终止任务移除队列;
6、手动触发一个isReady=NO的NSOperation会触发一个异常;

GCD:
1、针对多核进行了优化;
2、是使用最方便的一直多线程实现方式;
3、一般利用block实现,在代码连续性上更为简洁明了;
4、一旦触发就不能再监控和管理它的状态;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章