使用 GCD 在块内赋值
我正在执行一个不断从网站寻找更新的线程。应该可以在某些视图中设置刷新率。
更新线程不断检查更新间隔。但我想避免竞争条件。 (我什至需要担心 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);
}
});
我尝试实现这段代码。但是,它无法在块内分配“线程”变量。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于您给出的代码类型,我将使用队列上引发的计时器事件,而不是在代码中进行显式睡眠。这样你就不必担心竞争条件等。
当 autoRefresh 设置为 NO 时,你可以通过以下方式取消它:
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..
When the autoRefresh is set to NO, you can cancel it by