起因
這周開發(fā)過程中遇到一個奇怪的現(xiàn)象,即在某個頁面一直卡住停留腹缩,造成卡死。而又沒有立即崩潰空扎,等待一會兒后crash了藏鹊,當即猜想是陷入了死鎖或死循環(huán)里,于是開始排查转锈,最終發(fā)現(xiàn)是由于dispatch_once濫用導致死鎖盘寡。由于項目代碼過于復雜,現(xiàn)寫了個demo總結。
demo
1岸军、創(chuàng)建兩個單例(dispatch_once方式)
NSString *const ManagerOneRefreshNotification = @"ManagerOneRefreshNotification";
@implementation ManagerOne
+ (ManagerOne *)shareInstance {
static ManagerOne *shareInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [[ManagerOne alloc] init];
});
return shareInstance;
}
- (instancetype)init {
if (self = [super init]) {
self.unReadCount = 1;
[[NSNotificationCenter defaultCenter] postNotificationName:ManagerOneRefreshNotification object:nil];
}
return self;
}
@implementation ManagerTwo
+ (ManagerTwo *)shareInstance {
static ManagerTwo *shareInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shareInstance = [[ManagerTwo alloc] init];
});
return shareInstance;
}
- (instancetype)init {
if (self = [super init]) {
self.unReadCount = 2;
[[NSNotificationCenter defaultCenter] postNotificationName:ManagerTwoRefreshNotification object:nil];
}
return self;
}
2褪测、在他們初始化后都會利用通知回調(diào)給viewcontroller進行刷新
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:ManagerOneRefreshNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:ManagerTwoRefreshNotification object:nil];
[ManagerOne shareInstance];
}
- (void)refresh {
NSLog(@"unReadCount:%d", [ManagerOne shareInstance].unReadCount + [ManagerTwo shareInstance].unReadCount);
}
3、然后就會crash
分析
從左邊的調(diào)用棧中多次出現(xiàn)dispatch_once
和shareInstance
可以看出是進入了死循環(huán)影涉。根據(jù)調(diào)用棧中出現(xiàn)的_dispatch_client_callout
以及_dispatch_gate_wait_slow
猜想可能是dispatch_once_f
函數(shù)造成了信號量的永久等待,代碼更正思路好做规伐,但是為何會造成死鎖呢蟹倾?帶著疑問從dispatch_once
的源碼里尋找答案。
dispatch_once源碼
Apple對于dispatch_once的源碼地址
#include "internal.h"
#undef dispatch_once
#undef dispatch_once_f
typedef struct _dispatch_once_waiter_s {
volatile struct _dispatch_once_waiter_s *volatile dow_next;
dispatch_thread_event_s dow_event;
mach_port_t dow_thread;
} *_dispatch_once_waiter_t;
#define DISPATCH_ONCE_DONE ((_dispatch_once_waiter_t)~0l)
#ifdef __BLOCKS__
void
dispatch_once(dispatch_once_t *val, dispatch_block_t block)
{//第一步:我們調(diào)用dispatch_once入口猖闪,接下來去看最下面dispatch_once_f的定義
dispatch_once_f(val, block, _dispatch_Block_invoke(block));
}
#endif
#if DISPATCH_ONCE_INLINE_FASTPATH
#define DISPATCH_ONCE_SLOW_INLINE inline DISPATCH_ALWAYS_INLINE
#else
#define DISPATCH_ONCE_SLOW_INLINE DISPATCH_NOINLINE
#endif
DISPATCH_ONCE_SLOW_INLINE
static void
dispatch_once_f_slow(dispatch_once_t *val, void *ctxt, dispatch_function_t func)
{
#if DISPATCH_GATE_USE_FOR_DISPATCH_ONCE
dispatch_once_gate_t l = (dispatch_once_gate_t)val;
if (_dispatch_once_gate_tryenter(l)) {
_dispatch_client_callout(ctxt, func);
_dispatch_once_gate_broadcast(l);
} else {
_dispatch_once_gate_wait(l);
}
#else//第三步:主要的流程(為什么走#else請看注解二)
_dispatch_once_waiter_t volatile *vval = (_dispatch_once_waiter_t*)val;
struct _dispatch_once_waiter_s dow = { };
_dispatch_once_waiter_t tail = &dow, next, tmp;
dispatch_thread_event_t event;
//首次更改請求
if (os_atomic_cmpxchg(vval, NULL, tail, acquire)) {
dow.dow_thread = _dispatch_tid_self();
//調(diào)用dispatch_once內(nèi)block回調(diào)
_dispatch_client_callout(ctxt, func);
//利用while循環(huán)不斷處理未完成的更改請求鲜棠,直到所有更改結束
next = (_dispatch_once_waiter_t)_dispatch_once_xchg_done(val);
while (next != tail) {
tmp = (_dispatch_once_waiter_t)_dispatch_wait_until(next->dow_next);
event = &next->dow_event;
next = tmp;
_dispatch_thread_event_signal(event);
}
} else {//非首次更改請求
_dispatch_thread_event_init(&dow.dow_event);
next = *vval;
for (;;) {
//遍歷每一個后續(xù)請求,如果狀態(tài)已經(jīng)是Done培慌,直接進行下一個豁陆,同時該狀態(tài)檢測還用于避免在后續(xù)wait之前,信號量已經(jīng)發(fā)出(signal)造成的死鎖
if (next == DISPATCH_ONCE_DONE) {
break;
}
//如果當前dispatch_once執(zhí)行的block沒有結束吵护,那么就將這些后續(xù)請求添加到鏈表當中
if (os_atomic_cmpxchgv(vval, next, tail, &next, release)) {
dow.dow_thread = next->dow_thread;
dow.dow_next = next;
if (dow.dow_thread) {
pthread_priority_t pp = _dispatch_get_priority();
_dispatch_thread_override_start(dow.dow_thread, pp, val);
}
_dispatch_thread_event_wait(&dow.dow_event);
if (dow.dow_thread) {
_dispatch_thread_override_end(dow.dow_thread, val);
}
break;
}
}
_dispatch_thread_event_destroy(&dow.dow_event);
}
#endif
}
DISPATCH_NOINLINE
void
dispatch_once_f(dispatch_once_t *val, void *ctxt, dispatch_function_t func)
{
#if !DISPATCH_ONCE_INLINE_FASTPATH
if (likely(os_atomic_load(val, acquire) == DLOCK_ONCE_DONE)) {
return;
}
#endif //第二步:進入dispatch_once_f_slow(這個宏判斷請看注解一)
return dispatch_once_f_slow(val, ctxt, func);
}
注解一:
DISPATCH_ONCE_INLINE_FASTPATH
這個宏的值由CPU架構決定盒音,__x86_64__
(64位),__i386__
(32位)馅而,__s390x__
(運行在IBM z系統(tǒng)(s390x)祥诽,可能Apple和IBM比較熟,給他留后門了)用爪,以及__APPLE__
這個就無從得知了原押,可能是Apple自身的平臺架構,這些情況下DISPATCH_ONCE_INLINE_FASTPATH = 1
偎血,所以大部分情況也就是1了诸衔。
#if defined(__x86_64__) || defined(__i386__) || defined(__s390x__)
#define DISPATCH_ONCE_INLINE_FASTPATH 1
#elif defined(__APPLE__)
#define DISPATCH_ONCE_INLINE_FASTPATH 1
#else
#define DISPATCH_ONCE_INLINE_FASTPATH 0
#endif
注解二:
DISPATCH_GATE_USE_FOR_DISPATCH_ONCE
這個宏的值在lock.h
中有定義:
#pragma mark - gate lock
#if HAVE_UL_UNFAIR_LOCK || HAVE_FUTEX
#define DISPATCH_GATE_USE_FOR_DISPATCH_ONCE 1
#else
#define DISPATCH_GATE_USE_FOR_DISPATCH_ONCE 0
#endif
而HAVE_UL_UNFAIR_LOCK
的值和HAVE_FUTEX
的值也在lock.h
中有定義:
#ifdef __linux__
#define HAVE_FUTEX 1
#else
#define HAVE_FUTEX 0
#endif
#ifdef UL_UNFAIR_LOCK
#define HAVE_UL_UNFAIR_LOCK 1
#endif
從上面的分析可以看出:
1盯漂、dispatch_once不止是簡單的執(zhí)行一次,如果再次調(diào)用會進入非首次更改的模塊笨农,如果有未DONE的請求會被添加到鏈表中
2就缆、所以dispatch_once本質(zhì)上可以接受多次請求,會對此維護一個請求鏈表
3谒亦、如果在block執(zhí)行期間竭宰,多次進入調(diào)用同類的dispatch_once函數(shù)(即單例函數(shù)),會導致整體鏈表無限增長份招,造成永久性死鎖
4切揭、對于開始問題大致上和 A -> B -> A的流程類似,理解dispatch_once的內(nèi)部流程有利于在使用中規(guī)避隱藏的問題锁摔。