本文介绍了GCD:如何从两个线程写入和读取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这可能听起来像一个新手问题我是GCD的新手,
this may sound a newbie question anyway Im new to GCD,
我正在创建并运行以下两个线程。第一个将数据放入ivar mMutableArray
,第二个从中读取数据。如何锁定和取消线程以避免崩溃并保持代码线程安全?
I'm creating and running these two following threads. The first one puts data into ivar mMutableArray
and the second one reads from it. How do i lock and unclock the threads to avoid crashes and keep the code thread safe ?
// 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
You can still use @synchronized on your critical sections with GCD
这篇关于GCD:如何从两个线程写入和读取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!