我正在执行一个不断从网站寻找更新的线程。应该可以在某些 View 中设置刷新率。
更新线程不断检查更新间隔。但我想避免竞争条件。 (对于 GCD,我什至需要为此担心吗?)
//This variable is used to avoid race conditions, refreshRate is a instance variable
int threadRefreshRate = refreshRate;
BOOL autoRefresh = YES;
dispatch_async(autoUpdateQueue, ^ {
while(YES){
NSLog(@"Runs autoupdate thread");
dispatch_async(dispatch_get_main_queue(), ^{
if(autoRefresh){
[self checkForUpdate];
//Trying to set thread variable to avoid race condition
threadRefreshRate = refreshRate;
}
else
NSLog(@"Should not auto refresh");
});
sleep(threadRefreshRate);
}
});
我试图实现这段代码。然而,在一个 block 中赋值“thread”变量是行不通的。
最佳答案
对于您给出的那种代码,我会使用在队列中引发的计时器事件,而不是在代码中进行显式 sleep 。这样你就不必担心比赛条件等。
queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0);
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
if (!timer) return;
dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), refreshRate * NSEC_PER_SEC, 5 * NSEC_PER_SEC);
dispatch_source_t timer = self.timer;
//initialize self to blockSelf with __block
self.timerAction = ^{
[blockSelf checkForUpdate];
};
dispatch_source_set_event_handler(timer, timerAction);
dispatch_resume(timer);
当autoRefresh设置为NO时,可以通过
取消dispatch_source_cancel(timer);
关于ios - 使用 GCD 在 block 内赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6121557/