Replacing Threads with Dispatch Queues
Replacing Threads with Dispatch Queues
To understand how you might replace threads with dispatch queues, first consider some of the ways you might be using threads in your application today:
Single task threads. Create a thread to perform a single task and release the thread when the task is done.
Worker threads. Create one or more worker threads with specific tasks in mind for each. Dispatch tasks to each thread periodically.
Thread pools. Create a pool of generic threads and set up run loops for each one. When you have a task to perform, grab a thread from the pool and dispatch the task to it. If there are no free threads, queue the task and wait for a thread to become available.
Although these might seem like dramatically different techniques, they are really just variants on the same principle. In each case, a thread is being used to run some task that the application has to perform. The only difference between them is the code used to manage the threads and the queueing of tasks. With dispatch queues and operation queues, you can eliminate all of your thread and thread-communication code and instead focus on just the tasks you want to perform.
If you are using one of the above threading models, you should already have a pretty good idea of the type of tasks your application performs. Instead of submitting a task to one of your custom threads, try encapsulating that task in an operation object or a block object and dispatching it to the appropriate queue. For tasks that are not particularly contentious—that is, tasks that do not take locks—you should be able to make the following direct replacements:
For a single task thread, encapsulate the task in a block or operation object and submit it to a concurrent queue.
For worker threads, you need to decide whether to use a serial queue or a concurrent queue. If you use worker threads to synchronize the execution of specific sets of tasks, use a serial queue. If you do use worker threads to execute arbitrary tasks with no interdependencies, use a concurrent queue.
For thread pools, encapsulate your tasks in a block or operation object and dispatch them to a concurrent queue for execution.
Of course, simple replacements like this may not work in all cases. If the tasks you are executing contend for shared resources, the ideal solution is to try to remove or minimize that contention first. If there are ways that you can refactor or rearchitect your code to eliminate mutual dependencies on shared resources, that is certainly preferable. However, if doing so is not possible or might be less efficient, there are still ways to take advantage of queues. A big advantage of queues is that they offer a more predictable way to execute your code. This predictability means that there are still ways to synchronize the execution of your code without using locks or other heavyweight synchronization mechanisms. Instead of using locks, you can use queues to perform many of the same tasks:
If you have tasks that must execute in a specific order, submit them to a serial dispatch queue. If you prefer to use operation queues, use operation object dependencies to ensure that those objects execute in a specific order.
If you are currently using locks to protect a shared resource, create a serial queue to execute any tasks that modify that resource. The serial queue then replaces your existing locks as the synchronization mechanism. For more information techniques for getting rid of locks, see Eliminating Lock-Based Code.
If you use thread joins to wait for background tasks to complete, consider using dispatch groups instead. You can also use an
NSBlockOperation
object or operation object dependencies to achieve similar group-completion behaviors. For more information on how to track groups of executing tasks, see Replacing Thread Joins.If you use a producer-consumer algorithm to manage a pool of finite resources, consider changing your implementation to the one shown in Changing Producer-Consumer Implementations.
If you are using threads to read and write from descriptors, or monitor file operations, use the dispatch sources as described in Dispatch Sources.
It is important to remember that queues are not a panacea for replacing threads. The asynchronous programming model offered by queues is appropriate in situations where latency is not an issue. Even though queues offer ways to configure the execution priority of tasks in the queue, higher execution priorities do not guarantee the execution of tasks at specific times. Therefore, threads are still a more appropriate choice in cases where you need minimal latency, such as in audio and video playback.
https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW10
Replacing Threads with Dispatch Queues的更多相关文章
- Dispatch Queues and Thread Safety
Dispatch Queues and Thread Safety It might seem odd to talk about thread safety in the context of di ...
- iOS 并行编程:GCD Dispatch Queues
1 简介 1.1 功能 Grand Central Dispatch(GCD)技术让任务并行排队执行,根据可用的处理资源,安排他们在任何可用的处理器核心上执行任务.任务可以是一个函数 ...
- Dispatch Queues 线程池
Dispatch Queues Dispatch queues are a C-based mechanism for executing custom tasks. A dispatch queue ...
- Multithreading annd Grand Central Dispatch on ios for Beginners Tutorial-多线程和GCD的入门教程
原文链接:Multithreading and Grand Central Dispatch on iOS for Beginners Tutorial Have you ever written a ...
- Multithreading and Grand Central Dispatch on iOS for Beginners Tutorial
Have you ever written an app where you tried to do something, and there was a long pause while the U ...
- iOS 并发编程之 Operation Queues
现如今移动设备也早已经进入了多核心 CPU 时代,并且随着时间的推移,CPU 的核心数只会增加不会减少.而作为软件开发者,我们需要做的就是尽可能地提高应用的并发性,来充分利用这些多核心 CPU 的性能 ...
- iOS - Threads 多线程
1.Threads 1.1 进程 进程是指在系统中正在运行的一个应用程序.每个进程之间是独立的,每个进程均运行在其专用且受保护的内存空间内. 比如同时打开 QQ.Xcode,系统就会分别启动两个进程. ...
- GCD & Operation queues & Thread
One of the technologies for starting tasks asynchronously is Grand Central Dispatch (GCD). This tech ...
- usr/include/dispatch - dispatch_source
博文一部分摘自:Parse分析,以下简称博文1(LeanCloud工程师针对Parse使用GCD的分析) 博文一部分摘自:GCD入门,以下简称博文2 建议先了解一下:BSD基础知识 在Dispatch ...
随机推荐
- 最短的计算大数乘法的c程序
#include <stdio.h> char s[99],t[99]; int m,n; void r(int i,int c) { int j=0,k=i; while(k)c+=s[ ...
- 数据库数据在Java占用内存简单估算
数据库数据在Java占用内存简单估算 结论: 1.数据库记录放在JAVA里,用对象(ORM一般的处理方式)须要4倍左右的内存空间.用HashMap这样的KV保存须要10倍空间; 2.假设你主要数据是t ...
- MICRO SIM卡(SIM小卡)尺寸图及剪卡图解
如今使用MICRO SIM卡的手机越来越多.近期刚刚买了一个手机到手才发现尼马使用的是MICRO SIM卡.再去买剪卡器吧,十几二十块用一次就废了,去营业厅吧.又比較远,懒的出门.怎么办呢,自己剪!这 ...
- 第14章4节《MonkeyRunner源代码剖析》 HierarchyViewer实现原理-装备ViewServer-port转发
在初始化HierarchyViewer的实例过程中,HierarchyViewer会调用自己的成员方法setupViewServer来把ViewServer装备好,那么我们这里先看下这种方法: 39 ...
- 字节数组byte[]和整型,浮点型数据的转换——Java代码
近期在写C++ socket和java socket之间的通信程序,涉及到整数浮点数的传输.须要从字节数组还原数据,查了一些资料.总结例如以下 1. 整数和浮点数的机器表示 在机器内部.不 ...
- 在word中doc与docx的区别是什么(整理)
在word中doc与docx的区别是什么(整理) docx 是Office2007使用的,是用新的基于XML的压缩文件格式取代了其目前专有的默认文件格式,在传统的文件名扩展名后面添加了字母x(即.do ...
- Black Rock Shooter
在人气动漫 Black Rock shooter 中,当加贺里对麻陶 说出了"滚回去"以后,与此同时,在另一个心灵世界里, BRS 也遭到了敌人的攻击.此时,一共有 n 个攻击排成 ...
- POJ 3264 Balanced Lineup 区间最值
POJ3264 比较裸的区间最值问题.用线段树或者ST表都可以.此处我们用ST表解决. ST表建表方法采用动态规划的方法, ST[I][J]表示数组从第I位到第 I+2^J-1 位的最值,用二分的思想 ...
- Python三次登陆
题目:Python实现三次登陆 不要急于马上把三次登陆写出来,一定要将复杂的程序简单化,必须一步一步地去扩展,这样才保证不会出错. 步骤一:实现简单的一次登陆 # 事先定义 user = 'dark_ ...
- SQL service
依赖关系解决 ============================================================================================= ...