gpt4 book ai didi

iphone - GCD : How to write and read to variable from two threads

转载 作者:行者123 更新时间:2023-12-03 13:15:06 24 4
gpt4 key购买 nike

无论如何,这听起来可能是一个新手问题,对于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);
}

最佳答案

您仍然可以在GCD的关键部分使用@synchronized

关于iphone - GCD : How to write and read to variable from two threads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com