使用GCD在块内分配值

时间:2011-05-25 08:27:09

标签: ios objective-c-blocks grand-central-dispatch

我正在执行一个不断寻找网站更新的线程。应该可以在某个视图中设置刷新率。

更新线程不断检查更新的间隔。但我想避免竞争条件。 (我甚至不得不为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);
    }

});

我尝试实现此代码。但是,它不能用于在块内确定'thread'变量。

1 个答案:

答案 0 :(得分:2)

对于你给出的代码类型,我会使用队列中引发的计时器事件代替在代码中进行显式休眠。这样你就不用担心比赛条件等了。

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);