死鎖 1、 主隊列在主線程同步執(zhí)行
下列代碼寫在 viewDidLoad 中:
NSLog(@"before: %@", [NSThread currentThread]);
// 創(chuàng)建一個隊列(串行)
dispatch_queue_t q = dispatch_get_main_queue();
// 5 次異步
for (int index = 0; index < 5; index ++) {
// 將任務添加到隊列
dispatch_sync(q, ^{
NSLog(@"task : %@", [NSThread currentThread]);
});
}
NSLog(@"after: %@", [NSThread currentThread]);
打印結果:
2016-06-21 12:07:22.921 Thread-Objc[44793:2467944] before: <NSThread: 0x7fb84a500ac0>{number = 1, name = main}
測試的結果是 : 死鎖
關于死鎖:記住主隊列的特點就容易理解!主線程有任務就暫時不調度任務!
上面死鎖的寫法是: ** 主隊列在主線程同步執(zhí)行任務** 死鎖。
死鎖 2、
NSLog(@"before: %@", [NSThread currentThread]);
dispatch_queue_t q = dispatch_queue_create("q1", DISPATCH_QUEUE_SERIAL);
for (int index = 0; index < 10; index ++) {
dispatch_async(q, ^{
NSLog(@"async : %@", [NSThread currentThread]);
dispatch_sync(q, ^{
NSLog(@"sync :%@", [NSThread currentThread]);
});
});
}
NSLog(@"after: %@", [NSThread currentThread]);
打印結果:
2016-06-23 22:24:46.583 Thread-Objc[14719:2440315] before: <NSThread: 0x7fd989701580>{number = 1, name = main}
2016-06-23 22:24:46.583 Thread-Objc[14719:2440315] after: <NSThread: 0x7fd989701580>{number = 1, name = main}
2016-06-23 22:24:46.584 Thread-Objc[14719:2440510] async :<NSThread: 0x7fd98971c4b0>{number = 2, name = (null)}
上面死鎖的寫法是: 串行隊列異步執(zhí)行,根據(jù)特點會開 1 條線程,然后再在當前隊列線程進行同步執(zhí)行 死鎖。
死鎖的共同特點是: 在當前隊列的當前線程執(zhí)行同步任務, 死鎖!
在 dispatch_sync 函數(shù)的 AIP 中有這么一段解釋:
- Calls to dispatch_sync() targeting the current queue will result
- in dead-lock. Use of dispatch_sync() is also subject to the same
- multi-party dead-lock problems that may result from the use of a mutex.
- Use of dispatch_async() is preferred.
- 在當前隊列調用 dispatch_sync() 會造成死鎖。
- 在互斥鎖里面使用 dispatch_sync() 也會造成同樣的問題。
- 優(yōu)先考慮使用 dispatch_async()