GCD

下面这三篇文档讲了GCD使用的很多场景和技巧,感觉值得一看
https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html#//apple_ref/doc/uid/TP40008091-CH103-SW13
这个文档讲述了Dispatch Sources的使用。
dispatch source 将你想观察的事件,dispatch queue和处理事件响应的代码关联在一起,当你创建一个dispatch source时,它默认是挂起(suspend)状态,这让你有时间完成对他的配置,当你想让它响应事件时,你需要resum。
dispatch source会和一个queue关联,你可以change queue,但是如果你的事件已经加入了queue,那么该事件就会在之前的queue中执行,当执行完成后,后续的事件会在新的queue中去执行。
你可以给dispatch source设置一个取消事件的响应(Cancellation Handler),通常情况下,你不需要这么做,但是如果你需要做释放资源的操作,比如关闭一个文件描述符,那么你需要这样去操作
dispatch object是需要用户自己去管理引用计数的,如果你想持有或者销毁它,需要调用 dispatch_retain and dispatch_release函数
文档下半部分举了timer,socket(Reading data from a file、Writing data to a file、Watching for filename changes),Monitoring Signals、Monitoring Signals的例子,值得一看
https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html#//apple_ref/doc/uid/TP40008091-CH102-SW1
这个文档讲述了Dispatch Queues的使用
我们可以创建同步队列,并行队列,我们可以设定队列执行的优先级,向队列添加任务,我们可以设置在任务结束后执行某个block,我们可以使用dispatch_apply去代替for循环,我们可以对queue进行suspend和resume操作,我们可以使用信号量对有限的资源进行控制,我们可以使用group去进行同步操作,dispatch queue本身不需要用户进行release,retain操作,如果你这样做了,它会被简单的忽略,dispatch queue本身是线程安全的,注意gcd的死锁问题* Do not call the [dispatch_sync] function from a task that is executing on the same queue that you pass to your function call. Doing so will deadlock the queue. If you need to dispatch to the current queue, do so asynchronously using the [dispatch_async] function.当你想做顺序操作时,应当使用同步队列,而不是使用锁。Avoid taking locks from the tasks you submit to a dispatch queue. Although it is safe to use locks from your tasks, when you acquire the lock, you risk blocking a serial queue entirely if that lock is unavailable. Similarly, for concurrent queues, waiting on a lock might prevent other tasks from executing instead. If you need to synchronize parts of your code, use a serial dispatch queue instead of a lock.值得一看
https://developer.apple.com/library/archive/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW18
这个文档讲了如何从Thread迁移到GCD
其中使用dispatch_apply代替for循环,使用同步队列代替runloop,dispatch_sync正确使用都是不错的技巧,值得一看

你可能感兴趣的:(GCD)