(1)NSThread
(2)Cocoa NSOperation(NSOperation和NSOperationQueue)
(3)Grand Central dispath(GCD)
2,本文着重介绍NSThread
NSTread在三种多线程技术中是最轻量级的,但需要自己管理线程的生命周期和线程同步。线程同步对数据的加锁会有一定的系统开销。
3,NSThread的两种创建方式
(1)直接创建线程并且自动运行线程
(2)先创建一个线程对象,然后手动运行线程,在运行线程操作之前可以设置线程的优先级等线程信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
import
UIKit
class
ViewController
:
UIViewController
{
override
func
viewDidLoad() {
super
.viewDidLoad()
//方式1:使用类方法
NSThread
.detachNewThreadSelector(
"downloadImage"
,toTarget:
self
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,withObject:
nil
)
//方式2:实例方法-便利构造器
var
myThread:
NSThread
=
(target:
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,selector:
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,object:
)
myThread.start()
}
downloadImage(){
imageUrl =
"http://hangge.com/blog/images/logo.png"
data =
NSData
(contentsOfURL:
NSURL
(string: imageUrl)!,options:
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,error:
)
println
(data?.length)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
// dispose of any resources that can be recreated.
}
}
|
4,线程同步
//定义两个线程
thread1:
?
thread2:
?
//定义两个线程条件,用于锁住线程
let
condition1 =
NSCondition
()
condition2 =
NSCondition
()
viewDidLoad() {
.viewDidLoad()
thread2 =
"method2:"
)
thread1 =
"method1:"
)
thread1?.start()
}
method1(sender:
AnyObject
){
for
i=0; i<10; i++ {
print
(
"NSThread 1 running \(i)"
)
sleep(1)
if
i == 2 {
thread2?.start()
//启动线程2
//本线程(thread1)锁定
condition1.lock()
condition1.wait()
condition1.unlock()
}
}
"NSThread 1 over"
)
//线程2激活
condition2.signal()
}
//方法2
method2(sender:
){
i=0; i<10; i++ {
"NSThread 2 running \(i)"
)
sleep(1)
i == 2 {
//线程1激活
condition1.signal()
//本线程(thread2)锁定
condition2.lock()
condition2.wait()
condition2.unlock()
}
}
"NSThread 2 over"
)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
// dispose of any resources that can be recreated.
}
}
|
NSThread 1 running 0
NSThread 1 running 1
NSThread 1 running 2
NSThread 2 running 0
NSThread 2 running 1
NSThread 2 running 2
NSThread 1 running 3
NSThread 1 running 4
NSThread 1 running 5
NSThread 1 running 6
NSThread 1 running 7
NSThread 1 running 8
NSThread 1 running 9
NSThread 1 over
NSThread 2 running 3
NSThread 2 running 4
NSThread 2 running 5
NSThread 2 running 6
NSThread 2 running 7
NSThread 2 running 8
NSThread 2 running 9
NSThread 2 over
|
2,本文着重介绍Cocoa NSOperation
Cocoa NSOperation不需要关心线程管理和数据同步的事情,可以把精力放在自己需要执行的操作上。相关的类有NSOperation和NSOperationQueue。其中NSOperation是个抽象类,使用它必须用它的子类,可以实现它或者使用它定义好的子类:NSBlockOperation。创建NSOperation子类的对象,把对象添加到NSOperationqueue队列里执行。
Cocoa NSOperation不需要关心线程管理和数据同步的事情,可以把精力放在自己需要执行的操作上。相关的类有NSOperation和NSOperationQueue。其中NSOperation是个抽象类,使用它必须用它的子类,可以实现它或者使用它定义好的子类:NSBlockOperation。创建NSOperation子类的对象,把对象添加到NSOperationqueue队列里执行。
3,使用NSOperation的两种方式
(1)直接用定义好的子类:NSBlockOperation。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import
UIKit
class
ViewController
:
UIViewController
{
override
func
viewDidLoad() {
super
.viewDidLoad()
var
operation:
NSBlockOperation
=
NSBlockOperation
(block: { [
weak
self
]
in
?.downloadImage()
return
})
queue:
NSOperationQueue
=
NSOperationQueue
()
queue.addOperation(operation)
}
downloadImage(){
imageUrl =
"http://hangge.com/blog/images/logo.png"
data =
NSData
(contentsOfURL:
NSURL
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,options:
nil
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,error:
)
println
(data?.length)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
// dispose of any resources that can be recreated.
}
}
|
(2)继承NSOperation
然后把NSOperation子类的对象放入NSOperationqueue队列中,一旦这个对象被加入到队列,队列就开始处理这个对象,直到这个对象的所有操作完成,然后它被队列释放。
//创建线程对象
downloadImageOperation:
DownloadImageOperation
()
()
queue.addOperation(downloadImageOperation)
}
didReceiveMemoryWarning() {
.didReceiveMemoryWarning()
}
}
NSOperation
{
main(){
data =
NSData
(contentsOfURL:
NSURL
)
(data?.length)
}
}
|
4,设置运行队列并发数
可以设置线程池中的线程数,也就是并发操作数。默认情况下是-1,-1表示没有限制,这样可以同时运行队列中的全部操作。
//设置并发数
queue.maxConcurrentOperationCount = 5
|
5,取消队列所有操作
6,每个NSOperation完成都会有一个回调表示任务结束
//定义一个回调
completionBlock:(() ->
Void
)?
//给operation设置回调
operation.completionBlock = completionBlock
dispatch_after(dispatch_time(
disPATCH_TIME_Now
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,4),dispatch_get_main_queue(),{
(
"Complete"
)
})
|
2,本文着重介绍Grand Central dispath(GCD)
5
(2)获取系统存在的全局队列
1
(3)运行在主线程的Main dispatch Queue
GCD是Apple开发的一个多核编程的解决方法,基本概念就是dispatch queue(调度队列),queue是一个对象,它可以接受任务,并将任务以先到先执行的顺序来执行。dispatch queue可以是并发的或串行的。GCD的底层依然是用线程实现,不过我们可以不用关注实现的细节。其优点有如下几点:
(1)易用:GCD比thread更简单易用。基于block的特效使它能极为简单地在不同代码作用域之间传递上下文。
(2)效率:GCD实现功能轻量,优雅,使得它在很多地方比专门创建消耗资源的线程更加实用且快捷。
(4)安全:无需加锁或其他同步机制。
3,GCD三种创建队列的方法
(1)自己创建一个队列
第二个参数代表队列属于串行还是并行执行任务
并行队列的执行顺序与其加入队列的顺序相同。可以并发执行多个任务,但是执行完成的顺序是随机的。
//创建串行队列
serial:dispatch_queue_t = dispatch_queue_create(
"serialQueue1"
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
disPATCH_QUEUE_SERIAL
)
//创建并行队列
|
(2)获取系统存在的全局队列
Global dispatch Queue有4个执行优先级:
disPATCH_QUEUE_PRIORITY_HIGH 高
disPATCH_QUEUE_PRIORITY_DEFAULT 正常
disPATCH_QUEUE_PRIORITY_LOW 低
globalQueue:dispatch_queue_t = dispatch_get_global_queue(
disPATCH_QUEUE_PRIORITY_DEFAULT
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,0)
|
(3)运行在主线程的Main dispatch Queue
正如名称中的Main一样,这是在主线程里执行的队列。应为主线程只有一个,所有这自然是串行队列。一起跟UI有关的操作必须放在主线程中执行。
4,添加任务到队列的两种方法
1
(2)dispatch_sync同步追加Block块
5,暂停或者继续队列
6
6,dispatch_once 一次执行
7,dispatch_after 延迟调用
//延时2秒执行
8,多个任务全部结束后做一个全部结束的处理
10
8,dipatch_apply 指定次数的Block最加到指定队列中
9,信号,信号量
24
4,添加任务到队列的两种方法
//添加异步代码块到dispatch_get_global_queue队列
dispatch_async(dispatch_get_global_queue(
disPATCH_QUEUE_PRIORITY_DEFAULT
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,0),{ () ->
Void
in
//处理耗时操作的代码块...
println
(
"do work"
)
//操作完成,调用主线程来刷新界面
"main refresh"
)
})
})
|
同步追加Block块,与上面相反。在追加Block结束之前,dispatch_sync函数会一直等待,等待队列前面的所有任务完成后才能执行追加的任务。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
//不会造成死锁,当会一直等待代码块执行完毕
dispatch_sync(dispatch_get_global_queue(
disPATCH_QUEUE_PRIORITY_DEFAULT
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,{ () ->
Void
in
println
(
"sync1"
)
})
"end1"
)
//会引起死锁
//队列的末尾,要执行完成必须等前面的任务执行完成,由此又回到了第一步,程序卡死
"sync2"
)
})
"end2"
)
|
5,暂停或者继续队列
这两个函数是异步的,而且只在不同的blocks之间生效,对已经正在执行的任务没有影响。
而dispatch_resume则使得这些任务能够继续执行。
//创建并行队列
conQueue:dispatch_queue_t = dispatch_queue_create(
"concurrentQueue1"
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,
disPATCH_QUEUE_CONCURRENT
)
//暂停一个队列
dispatch_suspend(conQueue)
//继续队列
dispatch_resume(conQueue)
|
6,dispatch_once 一次执行
7,dispatch_after 延迟调用
dispatch_after并不是在指定时间后执行任务处理,而是在指定时间后把任务追加到dispatch Queue里面。因此会有少许延迟。注意,我们不能(直接)取消我们已经提交到dispatch_after里的代码。
8,多个任务全部结束后做一个全部结束的处理
dispatch_group_async:用来监视一组block对象的完成,你可以同步或异步地监视
dispatch_group_notify:用来汇总结果,所有任务结束汇总,不阻塞当前线程
dispatch_group_wait:等待直到所有任务执行结束,中途不能取消,阻塞当前线程
//获取系统存在的全局队列
queue:dispatch_queue_t = dispatch_get_global_queue(
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:1px 0px!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; font-family:Consolas,0)
//定义一个group
//并发任务,顺序执行
dispatch_group_async(group,queue,{() ->
in
"block1"
)
})
in
"block2"
)
})
ottom:auto!important; float:none!important; height:auto!important; left:auto!important; line-height:1.5em!important; margin:0px!important; overflow:visible!important; padding:0px 1em!important; position:static!important; right:auto!important; top:auto!important; vertical-align:baseline!important; width:auto!important; min-height:auto!important; background:none rgb(249,{() ->
in
"block3"
)
})
//所有任务执行结束汇总,不阻塞当前线程
dispatch_group_notify(group,153)!important; background:none!important">in
"group done"
)
})
//永久等待,直到所有任务执行结束,中途不能取消,阻塞当前线程
result = dispatch_group_wait(group,147)!important; background:none!important">disPATCH_TIME_FOREVER
)
if
result == 0{
"任务全部执行完成"
)
}
else
{
"某个任务还在执行"
)
}
|
8,dipatch_apply 指定次数的Block最加到指定队列中
dipatch_apply函数是dispatch_sync函数和dispatch Group的关联API。按指定的次数将指定的Block追加到指定的dispatch Queue中,并等待全部处理执行结束。
因为dispatch_apply函数也与dispatch_sync函数一样,会等待处理结束,因此推荐在dispatch_async函数中异步执行dispatch_apply函数。dispatch_apply函数可以实现高性能的循环迭代。
9,信号,信号量
dispatch_semaphore_waite:会判断信号量,如果为1,则往下执行。如果是0,则等待。
dispatch_semaphore_signal:代表运行结束,信号量加1,有等待的任务这个时候才会继续执行。
//当并行执行的任务更新数据时,会产生数据不一样的情况
for
i
in
1...20
{
"\(i)"
}
//使用信号量保证正确性
//创建一个初始计数值为1的信号
1...20
{
//永久等待,直到dispatch Semaphore的计数值 >= 1
dispatch_semaphore_wait(semaphore,monospace!important; min-height:auto!important; background:none!important">)
)
//发信号,使原来的信号计数值+1
dispatch_semaphore_signal(semaphore)
})
}
|
原文出自: www.hangge.com 转载请保留原文链接: http://www.hangge.com/blog/cache/detail_745.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。