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、一旦觸發就不能再監控和管理它的狀態;

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