28

通过信号量实现异步调用转同步

 3 years ago
source link: https://kangzubin.com/semaphore-async-to-sync/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在 iOS 开发中,我们通常会通过 delegate 或者 block 的方式来实现异步回调。如图 1 所示,在异步方法 doSomethingWithCallback: 中执行一些耗时操作,然后通过执行 callback block 将结果返回给调用者,并执行后续的逻辑。

YvYvMzy.jpg!web

这是一种很常见的写法,它的好处就是使代码看起来很紧凑,统一在回调 block 中处理异步结果,但缺点就是,如果结果处理逻辑很复杂,就会使 callback block 里的代码很冗长,且如果结果处理过程中又需要调用其他异步方法,很容易出现 block 嵌套的情况。

下面介绍介绍一种通过信号量 semaphore 把异步调用转成同步调用的方式,代码如图 2 中红框所示:我们先创建一样信号量,初始值为 0,然后调用异步方法,接着通过 dispatch_semaphore_wait 实现加锁等待,在回调 block 中保存结果数据,并通过 dispatch_semaphore_signal 实现解锁,最后再统一处理结果,整个流程看起来就相当于一次同步调用了。

jqQZFnY.jpg!web

虽然使用起来有点麻烦,但是在有些场景下我们确实可能需要把异步逻辑转成同步,希望能帮到你。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK