讀取變量,這可能聽起來新手的問題,反正進出口新的GCD,GCD:如何編寫,並從兩個線程
我創建和運行這兩個以下線程。第一個將數據放入ivar mMutableArray
,第二個從中讀取數據。我如何鎖定和解鎖線程以避免崩潰並保持代碼線程安全?
// Thread for writing data into mutable array
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (timer) {
dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * interval), interval * NSEC_PER_SEC, leeway);
dispatch_source_set_event_handler(timer, ^{
...
// Put data into ivar
[mMutableArray addObject:someObject];
...
});
dispatch_resume(timer);
}
// Thread for reading from mutable array
dispatch_source_t timer1 = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (timer1) {
dispatch_source_set_timer(timer1, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * interval), interval * NSEC_PER_SEC, leeway);
dispatch_source_set_event_handler(timer1, ^{
...
if (mMutableArray) {
// Read data from ivar
SomeObject* someobject = [mMutableArray lastObject];
}
...
});
dispatch_resume(timer1);
}
爲了清楚'@synchronized',GCD不執行「停止世界」的同步。它只會**停止所有其他線程訪問您的關鍵部分/ s **。這通常是你想要的。 – Barry