原创Blog,转载请注明出处
http://blog.csdn.net/hello_hwc?viewmode=contents
一 何为信号量?
简单来说就是控制访问资源的数量,比如系统有两个资源可以被利用,同时有三个线程要访问,只能允许两个线程访问,第三个应当等待资源被释放后再访问。
注意:再GCD中,只有调度的线程在信号量不足的时候才会进入内核态进行线程阻塞
二 如何使用信号量
三个主要函数
创建一个信号量
- funcdispatch_semaphore_create(_value:Int)->dispatch_semaphore_t!
其中value为信号量的初值,如果小于0则会返回NULL
提高信号量
copy
funcdispatch_semaphore_signal(_dsema:dispatch_semaphore_t!)->Int
等待降低信号量
copy
funcdispatch_semaphore_wait(_dsema:dispatch_semaphore_t!,
- _timeout:dispatch_time_t)->Int
注意,正常的使用顺序是先降低然后再提高,这两个函数通常成对使用。
三 举例分析
<prename="code"class="objc">//
- //ViewController.swift
- //SwiftTestExample
- //
- //Createdbyhuangwenchenon15/1/6.
- //Copyright(c)2015年huangwenchen.Allrightsreserved.
- //
-
- importUIKit
- classViewController:UIViewController{
- varsemaphore:dispatch_semaphore_t;
- requiredinit(coderaDecoder:NSCoder){
- self.semaphore=dispatch_semaphore_create(1)
- super.init(coder:aDecoder)
- }
- overridefuncviewDidLoad(){
- super.viewDidLoad()
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),{()->Voidin
- self.task_first()
- })
- dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,{()->Voidin
- self.task_second()
- })
- self.task_third()
- //Doanyadditionalsetupafterloadingtheview,typicallyfromanib.
- }
- functask_first(){
- dispatch_semaphore_wait(self.semaphore,DISPATCH_TIME_FOREVER)
- NSLog("%@","Firsttaskstarting")
- sleep(1)
- dispatch_semaphore_signal(self.semaphore)
- functask_second(){
- dispatch_semaphore_wait(self.semaphore,DISPATCH_TIME_FOREVER)
- NSLog("%@","Secondtaskstarting")
- sleep(1)
- dispatch_semaphore_signal(self.semaphore)
- functask_third(){
- overridefuncdidReceiveMemoryWarning(){
- super.didReceiveMemoryWarning()
- //DispoSEOfanyresourcesthatcanberecreated.
-
- }
这段代码模拟提交三个任务,提交到全局队列(并行队列)
当信号量的初初始为2时候
输出
2015-01-0619:42:01.963SwiftTestExample[632:11631]Firsttaskstarting
- 2015-01-0619:42:01.964SwiftTestExample[632:11630]Secondtaskstarting
- 19:42:02.971SwiftTestExample[632:11630]Secondtaskisdone
- 19:42:02.971SwiftTestExample[632:11631]Firsttaskisdone
- 19:42:02.971SwiftTestExample[632:11633]Thridtaskstarting
- 19:42:03.974SwiftTestExample[632:11633]Thridtaskisdone
当信号量为3的时候
copy
19:42:49.912SwiftTestExample[666:12259]Firsttaskstarting
- 19:42:49.912SwiftTestExample[666:12258]Secondtaskstarting
- 19:42:49.912SwiftTestExample[666:12260]Thridtaskstarting
- 19:42:50.915SwiftTestExample[666:12259]Firsttaskisdone
- 19:42:50.915SwiftTestExample[666:12260]Thridtaskisdone
- 19:42:50.915SwiftTestExample[666:12258]Secondtaskisdone
当信号量为1的时候
copy
19:43:35.140SwiftTestExample[694:12768]Firsttaskstarting
- 19:43:36.145SwiftTestExample[694:12768]Firsttaskisdone
- 19:43:36.145SwiftTestExample[694:12771]Secondtaskstarting
- 19:43:37.146SwiftTestExample[694:12771]Secondtaskisdone
- 19:43:37.146SwiftTestExample[694:12769]Thridtaskstarting
- 19:43:38.150SwiftTestExample[694:12769]Thridtaskisdone
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|