在访问数据库时使用Serial Dispatch Queue队列时可避免数据竞争问题。写入处理确实不可以和其他的写入和读取处理并行执行,但是读取处理与读取处理可以并行执行。在3用dispatch_barrier_async
例如:
dispatch_queue_t concurrentQueue1= dispatch_queue_create(\"www.goole.com\", DISPATCH_QUEUE_CONCURRENT);
/********************模拟读取操作********************/
dispatch_async(concurrentQueue1, ^{
for (int i=0; i<1000; i++) {
int index=arc4random()%12;
NSLog(@\"读取任务-%@\",self.array[index]);
}
});
dispatch_async(concurrentQueue1, ^{
for (int i=0; i<1000; i++) {
int index=arc4random()%12;
NSLog(@\"读取任务二%@\",self.array[index]);
}
});
dispatch_async(concurrentQueue1, ^{
for (int i=0; i<1000; i++) {
int index=arc4random()%12;
NSLog(@\"读取任务三%@\",self.array[index]);
}
});
/********************模拟写入操作********************/
dispatch_barrier_async(concurrentQueue1, ^{
[self.array removeAll s];
[self.array add sFromArray:@[@\"aaa\",@\"bbb\",@\"ccc\",@\"ddd\",@\"eee\",@\"qqq\",@\"ccc\",@\"fff\",@\"ggg\",@\"rrr\",@\"bbb\",@\"jjj\"]];
});
dispatch_async(concurrentQueue1, ^{
for (int i=0; i<100; i++) {
int index=arc4random()%12;
NSLog(@\"读取任务四%@\",self.array[index]);
}
});
dispatch_async(concurrentQueue1, ^{
for (int i=0; i<100; i++) {
int index=arc4random()%12;
NSLog(@\"读取任务五%@\",self.array[index]);
}
});
dispatch_async(concurrentQueue1, ^{
for (int i=0; i<100; i++) {
int index=arc4random()%12;
NSLog(@\"读取任务六%@\",self.array[index]);
}
});
//结论:打印结果会是 读取任务一二三 执行完之后 执行写入操作,写入操作执行完之后最后执行 读取任务四五六
继续阅读与本文标签相同的文章
-
云原生技术之Docker入门
2026-05-18栏目: 教程
-
点我达与满电未来达成合作协议
2026-05-18栏目: 教程
-
光明日报:聚集高端产业 加速双向开放
2026-05-18栏目: 教程
-
绩效管理如何做?简单绩效考核管理应用分享
2026-05-18栏目: 教程
-
学再多Excel的高级技能,都不如这三款可视化特效组件有用
2026-05-18栏目: 教程
