dispatch_barrier_async 中的代码未执行
Code within dispatch_barrier_async not executing
我尝试了一个简单的例子来学习使用 dispatch-barrier async。基本上,一个带有 ViewDidLoad 的单视图 iOS 应用程序如下所示。三个任务被提交到一个并发队列。其中两个读取变量,而第三个写入变量。
我看到写入永远不会执行(即 X = X + 10 永远不会执行。)如果我只是使用 dispatch_async 提交它(而不是在 dispatch_barrier_async 中保护它)如最后一段代码所示,它可以工作。 (令人惊讶的是,即使我不使用 disaptch_barrier_async 保护它,也没有在读取 X 的同时写入 X 的问题)。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
dispatch_queue_t backgroundQueue;
__block int X = 10;
backgroundQueue = dispatch_queue_create("com.smarthome.readwriteQ", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(backgroundQueue, ^{
while (1) {
NSLog(@"Task 1: X = %d",X);
[NSThread sleepForTimeInterval:4];
}
});
dispatch_async(backgroundQueue, ^{
while (1) {
NSLog(@"Task 2: X = %d",X);
[NSThread sleepForTimeInterval:4];
}
});
//This does not work
dispatch_barrier_async(backgroundQueue,^(void){
while (1) {
X = X + 10;
NSLog(@"Task 3: After Writing X = %d",X);
[NSThread sleepForTimeInterval:2];
}
});
//This works
dispatch_async(backgroundQueue,^(void){
while (1) {
X = X + 10;
NSLog(@"Task 3: After Writing X = %d",X);
[NSThread sleepForTimeInterval:2];
}
});
}
我想我没有正确理解dispatch_barrier_async。任何指针将不胜感激。
When it encounters a barrier, a concurrent queue delays the execution of the barrier block (or any further blocks) until all blocks submitted before the barrier finish executing.
您提交了两个 永远不会 完成执行的块,然后提交了屏障块。所以GCD从不执行屏障块。
我尝试了一个简单的例子来学习使用 dispatch-barrier async。基本上,一个带有 ViewDidLoad 的单视图 iOS 应用程序如下所示。三个任务被提交到一个并发队列。其中两个读取变量,而第三个写入变量。
我看到写入永远不会执行(即 X = X + 10 永远不会执行。)如果我只是使用 dispatch_async 提交它(而不是在 dispatch_barrier_async 中保护它)如最后一段代码所示,它可以工作。 (令人惊讶的是,即使我不使用 disaptch_barrier_async 保护它,也没有在读取 X 的同时写入 X 的问题)。
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
dispatch_queue_t backgroundQueue;
__block int X = 10;
backgroundQueue = dispatch_queue_create("com.smarthome.readwriteQ", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(backgroundQueue, ^{
while (1) {
NSLog(@"Task 1: X = %d",X);
[NSThread sleepForTimeInterval:4];
}
});
dispatch_async(backgroundQueue, ^{
while (1) {
NSLog(@"Task 2: X = %d",X);
[NSThread sleepForTimeInterval:4];
}
});
//This does not work
dispatch_barrier_async(backgroundQueue,^(void){
while (1) {
X = X + 10;
NSLog(@"Task 3: After Writing X = %d",X);
[NSThread sleepForTimeInterval:2];
}
});
//This works
dispatch_async(backgroundQueue,^(void){
while (1) {
X = X + 10;
NSLog(@"Task 3: After Writing X = %d",X);
[NSThread sleepForTimeInterval:2];
}
});
}
我想我没有正确理解dispatch_barrier_async。任何指针将不胜感激。
When it encounters a barrier, a concurrent queue delays the execution of the barrier block (or any further blocks) until all blocks submitted before the barrier finish executing.
您提交了两个 永远不会 完成执行的块,然后提交了屏障块。所以GCD从不执行屏障块。