Dispatch Group机制——笔记

本文是《Effective Objective-C 2.0》的读书笔记,聚焦于Dispatch Group这一GCD特性。Dispatch Group允许开发者将多个任务分组,并在所有任务完成时得到通知。文中介绍了如何创建Dispatch Group,以及使用`dispatch_group_async`、`dispatch_group_enter`/`dispatch_group_leave`的两种任务分组方式。此外,对比了`dispatch_group_wait`和`dispatch_group_notify`的异同,前者会阻塞线程,后者则在非阻塞方式下执行后续任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《Effective Objective-C 2.0  编写高质量iOS与OS X代码的52个有效方法》(第四十四条:通过Dispatch Group机制,根据系统资源状况来执行任务)笔记

要点如下:

1、dispatch group是GCD的一项特性,可以把任务分组。这组任务完成后时,调用者会收到通知

据此,可将要并发执行的多个任务合并为一组,这样调用者就可以知道这些任务何时能全部执行完

2、创建dispatch group:

dispatch_group_t dispatchGroup = dispatch_group_create();

3、将任务分组的两种方式:

方式一、用dispatch_group_async:

void dipatch_group_async(dispatch_group_t group, dispatch_queue_t queue, dispatch_block_t block); 
//比dispatch_async多了group分组这个参数

方式二、用dispatch_group_enter和dispatch_group_leave:

void dispatch_group_enter(dispatch_group_t group); //使分组里正要执行的任务数递增

void dispatch_group_leave(dispatch_group_t group); //使分组里的任务数递减

dispatch_group_enter和dispatch_group_leave就相当于

Swift DispatchGroup is a class in the Swift programming language that allows you to synchronize the execution of multiple tasks running on different threads. It helps you to manage the timing of asynchronous operations and avoid race conditions. A DispatchGroup is a lightweight mechanism for tracking a group of tasks. You can add tasks to a group, and the group will notify you when all of the tasks have completed. You can also specify a timeout for the group, after which the group will notify you if any of the tasks have not completed. Here is an example of how to use a DispatchGroup: ``` let group = DispatchGroup() group.enter() // run task 1 group.leave() group.enter() // run task 2 group.leave() group.notify(queue: .main) { // both tasks have completed } ``` In this example, we create a DispatchGroup called `group`. We then use the `enter()` and `leave()` methods to add two tasks to the group. The `notify()` method is called when both tasks have completed, and we can then perform any necessary actions. You can also use a DispatchGroup to wait for a group of tasks to complete before continuing execution. Here's an example: ``` let group = DispatchGroup() group.enter() // run task 1 group.leave() group.enter() // run task 2 group.leave() group.wait() // both tasks have completed ``` In this example, we use the `wait()` method to wait for both tasks to complete before continuing execution. This can be useful if you need to ensure that all tasks have completed before performing additional actions.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值