Assigning values within block with GCD
Im executing a thread that keeps looking for updates from a web site. It should be possible to set the refresh rate in some view.
The update thread keeps checking for a updated interval. But I would like to avoid race conditions. (Do I even have to worry for this with 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);
}
});
I tried to implement this code. However it doesn't work to assing the 'thread'-variable within a block.
For the kind of code you have given, i would use the timer events raised on the queue instead doing explicit sleep in the code. This way you dont have to worry about the race conditions etc..
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);
When the autoRefresh is set to NO, you can cancel it by
dispatch_source_cancel(timer);
精彩评论