多線程的"加鎖"和GCD案例

回顧:(多線程的執(zhí)行原理 )同一時間, CPU只能運行一條線程, 只有一條線程在工作, 多線程的原理其實是CPU在各個不同的線程之間不停地做切換, 因為執(zhí)行切換的時間非常快, 造成了同時執(zhí)行的假象.

為什么要用多線程 : 當一個應(yīng)用程序只有單個主線程工作時, 如果加載耗時任務(wù):(比如說 : 顯卡/音頻等等 I/O 設(shè)備), 線程會執(zhí)行的很慢, 這就會影響到用戶的體驗, 所以將任務(wù)分多個線程來執(zhí)行

iOS中多線程的實現(xiàn)

(方案1).pthread (跨平臺的C語言框架, 生命周期手動管理, 不用)

(方案2).NSThread (OC, 生命周期手動管理, 可直接操作線程對象)

#pragma mark  (1) 直接創(chuàng)建一個帶方法的線程
  NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(longOperation:) object:@"thread"];
// 還需要手動調(diào)用 start 方法來開啟線程
  [thread start];

#pragma mark  (2) 通過此方式無法拿到真的線程 
  [NSThread detachNewThreadSelector:(nonnull SEL) toTarget:(nonnull id) withObject:(nullable id)] ;

#pragma mark  (3) 隱式創(chuàng)建線程來執(zhí)行方法
  [self performSelector:(SEL)aSelector withObject:(id)arg];
NSThread 幾種線程操作:

(1).-(void)cancel : API : Changes the cancelled state of the receiver to indicate that it should exit. 翻譯 : 改變線程的狀態(tài)來標識它應(yīng)該處于退出狀態(tài).
注意: 這種方式僅僅改變線程的狀態(tài), 并不一定就使得線程退出, 一般不這么用.
(2).[NSThread sleepForTimeInterval:(NSTimeInterval)] //休眠指定時長
[NSThread sleepUntilDate:(nonnull NSDate )] //休眠到指定的日期
以上2個方法會使得線程處于阻塞狀態(tài), 讓線程的循環(huán)對象源暫停循環(huán)
(3).
[thread exit]* //終止當前線程
Before exiting the thread, this method posts the [NSThreadWillExitNotification] with the thread being exited to the default notification center. Because notifications are delivered synchronously, all observers of [NSThreadWillExitNotification] are guaranteed to receive the notification before the thread exits.

一個循環(huán)對象從線程被調(diào)用開始, 會一直轉(zhuǎn)圈檢查有沒有事件發(fā)生.png

Figure 3-1 shows the conceptual structure of a run loop and a variety of sources. The input sources deliver asynchronous events to the corresponding handlers and cause the [runUntilDate:]
method (called on the thread’s associated [NSRunLoop] object) to exit. Timer sources deliver events to their handler routines but do not cause the run loop to exit.

當多個線程訪問同一變量的時候, 會造成什么現(xiàn)象? 如何解決?

互斥鎖的概念: 給訪問和操作這個單一變量的代碼, 加一把鎖.

#import "ViewController.h"
@interface ViewController ()
//票
@property(atomic,assign) int tickets;
//鎖
@property(nonatomic,strong) NSObject *obj;
@end
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tickets = 5;
    self.obj = [[NSObject alloc] init];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    //模擬賣票窗口
    NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    [thread1 start];    
    NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets) object:nil];
    [thread2 start];
}
- (void)sellTickets {
    while (YES) {
        // @synchronized(obj)括號里填任意的對象(鎖),  這個對象(鎖)必須是同一個對象
        @synchronized(self.obj) {
            if(self.tickets > 0){
                self.tickets = self.tickets - 1;
                NSLog(@"余票%d %@",self.tickets,[NSThread currentThread]);
                continue;
            }
        }
        NSLog(@"沒有票了");
        break;
    }
}
@end
隱式創(chuàng)建子線程, 實現(xiàn)線程間通訊

在后臺線程下載圖像
[self performSelectorInBackground:@selector(downloadImage) withObject:nil];
在主線程設(shè)置圖像
[self performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];

(方案3).GCD : 全稱是(§Grand Central Dispatch)

GCD 的優(yōu)點: (1). (§純C語言, 提供了非常多強大的函數(shù)) 是蘋果公司為多核的并行運算提出的解決方案, 旨在替代NSThread等線程技術(shù), 充分利用設(shè)備的CPU內(nèi)核

(2). GCD自動管理線程的聲明周期 (創(chuàng)建線程, 調(diào)度任務(wù), 銷毀線程), 程序員只要告訴GCD要執(zhí)行什么任務(wù), 無需自己管理線程.

GCD使用的兩步: (1).定制任務(wù) (2).把任務(wù)添加到隊列中

GCD兩種調(diào)度任務(wù)的方式:

(1) "異步方式" :
dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSLog(@" 1 - %@",[NSThread currentThread]); });

(2) "同步方式" :
dispatch_sync(dispatch_get_global_queue(0, 0), ^{ NSLog(@" 2 - %@",[NSThread currentThread]); });

兩種方式的對比:

異步方式: <1>一定會開啟子線程執(zhí)行 block 任務(wù) <2>不用等待當前語句執(zhí)行完畢,就可以執(zhí)行下一條語句 (就像下餃子一樣,一下子倒到鍋里)

同步方式: <1>不會開啟線程 <2>必須等待當前的任務(wù)執(zhí)行完畢,才會執(zhí)行下一個任務(wù)

GCD的三種隊列:

(1) 串行隊列 : (自己創(chuàng)建/主隊列) 特點 : 一次只能"調(diào)度"一個任務(wù)

(2) 并發(fā)隊列 : (自己創(chuàng)建/全局隊列) 特點 : 一次可以"調(diào)度"多個任務(wù)

(3) 主隊列 : 一個特殊的串行隊列, 相當于主線程 (在主線程空閑時才會調(diào)度隊列中的任務(wù)在主線程上執(zhí)行)

GCD進行線程間測試

- (void)viewDidLoad {
    [super viewDidLoad];
    [self demo2];
}
- (void)demo2 {
    dispatch_queue_t temp = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_sync(temp, ^{
        NSLog(@" 1--> %@",[NSThread currentThread]);
#warning 異步串行
        dispatch_async(temp, ^{
            NSLog(@" 2--> %@",[NSThread currentThread]);
        });
        NSLog(@"3333333333333");
    });
#warning 同步并發(fā)
    dispatch_sync(dispatch_get_global_queue(0, 0), ^{ 
        NSLog(@" 3--> %@",[NSThread currentThread]);
        dispatch_sync(temp, ^{
            NSLog(@" 4--> %@",[NSThread currentThread]);
        });
    });
}

如圖所示的任務(wù)2是在任務(wù)1內(nèi)被添加到串行隊列中的, 由于是串行隊列, 所以必須在任務(wù)1之后才執(zhí)行, 所以先打印"333333",然后打印"3" 或"2", 任務(wù)2和任務(wù)3的順序是不固定的, 但是經(jīng)過試驗很多次發(fā)現(xiàn),任務(wù)3先執(zhí)行的概率大一些, 分析原因可能是主線程的優(yōu)先級更高, 任務(wù)四在串行隊列最末, 最后執(zhí)行.

幾種執(zhí)行方式的試驗.png

GCD小錯誤demo

串行同步方式導致死鎖

- (void)viewDidLoad {
    [super viewDidLoad];
    [self demo3];
}
-(void)demo3 {
    dispatch_queue_t temp = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);   
    dispatch_sync(temp, ^{
        NSLog(@" 1--> %@",[NSThread currentThread]);
        **warning 在當前這個串行隊列中有兩個任務(wù),使用同步方式運行會造成死鎖**
        dispatch_sync(temp, ^{     
            NSLog(@" 2--> %@",[NSThread currentThread]);
        });
        NSLog(@"333");
    });    
}
同步串行隊列死鎖舉例.png

問題的總結(jié) : 由于使用同步的方式來執(zhí)行串行隊列中的任務(wù), 導致了只能夠順序地執(zhí)行隊列里的任務(wù), 這時我們的隊列temp中有兩個同步任務(wù), 而且是嵌套執(zhí)行的. 這時當UI線程執(zhí)行到第二個同步任務(wù)時, 就會等待第一個任務(wù)執(zhí)行完畢, 可是第二個任務(wù)是嵌套在第一個任務(wù)內(nèi)的, 因此造成了死鎖.

解決方案:

#warning 解決方案:將兩個任務(wù)中的任意一個的隊列改成其他的隊列
- (void)viewDidLoad {
    [super viewDidLoad];
    [self demo3];
}
-(void)demo3 {
  dispatch_queue_t temp = dispatch_queue_create("serial", DISPATCH_QUEUE_SERIAL);
  dispatch_sync(dispatch_get_global_queue(0, 0), ^{ 
        NSLog(@" 3--> %@",[NSThread currentThread]);
        dispatch_sync(temp, ^{
            NSLog(@" 4--> %@",[NSThread currentThread]);
        });
    });
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容