swift版的GCD封装

说明

本人针对swift封装了GCD,包括GCDQueue,GCDGroup,GCDTimer以及GCDSemaphore,使用较为便利.

源码

https://github.com/YouXianMing/Swift-GCD

//
// GCDQueue.swift
// GCD
//
// http://home.cnblogs.com/u/YouXianMing/
// https://github.com/YouXianMing
//
// Created by YouXianMing on 15/10/9.
// import UIKit enum QueueType { case SerialQueue, // 串行线程队列
ConcurrentQueue, // 并发线程队列
None // 无类型
} class GCDQueue: NSObject { // MARK: 变量
var dispatchQueue : dispatch_queue_t! // MARK: 初始化
override init() { super.init()
dispatchQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
} init(queueType : QueueType) { super.init() switch queueType { case .SerialQueue: dispatchQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
break case .ConcurrentQueue: dispatchQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
break case .None: dispatchQueue = nil
break
}
} // MARK: 单例
static let mainQueue : GCDQueue = { let instance = GCDQueue(queueType: .None)
instance.dispatchQueue = dispatch_get_main_queue() return instance
}() static let globalQueue : GCDQueue = { let instance = GCDQueue(queueType: .None)
instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ) return instance
}() static let highPriorityGlobalQueue : GCDQueue = { let instance = GCDQueue(queueType: .None)
instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, ) return instance
}() static let lowPriorityGlobalQueue : GCDQueue = { let instance = GCDQueue(queueType: .None)
instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, ) return instance
}() static let backgroundPriorityGlobalQueue : GCDQueue = { let instance = GCDQueue(queueType: .None)
instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, ) return instance
}() // MARK: 执行 /**
Submits a block for asynchronous execution on a dispatch queue and returns immediately. - parameter block: dispatch block
*/
func excute(block : dispatch_block_t) { dispatch_async(dispatchQueue, block)
} func excute(block : dispatch_block_t, afterDelayWithNanoseconds : Int64) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, afterDelayWithNanoseconds), dispatchQueue, block)
} /**
Submits a block object for execution on a dispatch queue and waits until that block completes. - parameter block: dispatch block
*/
func waitExecute(block : dispatch_block_t) { dispatch_sync(dispatchQueue, block)
} /**
Submits a barrier block for asynchronous execution and returns immediately. - parameter block: dispatch block
*/
func barrierExecute(block : dispatch_block_t) { dispatch_barrier_async(dispatchQueue, block)
} /**
Submits a barrier block object for execution and waits until that block completes. - parameter block: dispatch block
*/
func waitBarrierExecute(block : dispatch_block_t) { dispatch_barrier_sync(dispatchQueue, block)
} // MARK: 便利构造器方法
class func executeInMainQueue(block : dispatch_block_t) { dispatch_async(mainQueue.dispatchQueue, block)
} class func executeInGlobalQueue(block : dispatch_block_t) { dispatch_async(globalQueue.dispatchQueue, block)
} class func executeInHighPriorityGlobalQueue(block : dispatch_block_t) { dispatch_async(highPriorityGlobalQueue.dispatchQueue, block)
} class func executeInLowPriorityGlobalQueue(block : dispatch_block_t) { dispatch_async(lowPriorityGlobalQueue.dispatchQueue, block)
} class func executeInBackgroundPriorityGlobalQueue(block : dispatch_block_t) { dispatch_async(backgroundPriorityGlobalQueue.dispatchQueue, block)
} class func executeInMainQueue(block : dispatch_block_t, afterDelaySeconds : Double) { let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), mainQueue.dispatchQueue, block)
} class func executeInGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) { let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), globalQueue.dispatchQueue, block)
} class func executeInHighPriorityGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) { let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), highPriorityGlobalQueue.dispatchQueue, block)
} class func executeInLowPriorityGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) { let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), lowPriorityGlobalQueue.dispatchQueue, block)
} class func executeInBackgroundPriorityGlobalQueue(block : dispatch_block_t, afterDelaySeconds : Double) { let delayTime : Int64 = Int64(afterDelaySeconds * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, delayTime), backgroundPriorityGlobalQueue.dispatchQueue, block)
} // MARK: 恢复与挂起
func suspend() { dispatch_suspend(dispatchQueue)
} func resume() { dispatch_resume(dispatchQueue)
} // MARK: GCDGroup相关
func excute(block : dispatch_block_t, inGroup : GCDGroup!) { dispatch_group_async(inGroup.dispatchGroup, dispatchQueue, block)
} func notify(block : dispatch_block_t, inGroup : GCDGroup!) { dispatch_group_notify(inGroup.dispatchGroup, dispatchQueue, block)
}
}
//
// GCDGroup.swift
// GCD
//
// http://home.cnblogs.com/u/YouXianMing/
// https://github.com/YouXianMing
//
// Created by YouXianMing on 15/10/9.
// import UIKit class GCDGroup: NSObject { // MARK: 变量
var dispatchGroup : dispatch_group_t! // MARK: 初始化
override init() { super.init()
dispatchGroup = dispatch_group_create()
} // MARK: 操作
func enter() { dispatch_group_enter(dispatchGroup)
} func leave() { dispatch_group_leave(dispatchGroup)
} func wait() { dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER)
} func waitWithNanoseconds(nanoseconds : Int64) -> Bool { return dispatch_group_wait(dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, nanoseconds)) ==
}
}
//
// GCDTimer.swift
// GCD
//
// http://home.cnblogs.com/u/YouXianMing/
// https://github.com/YouXianMing
//
// Created by YouXianMing on 15/10/9.
// import UIKit class GCDTimer: NSObject { // MARK: 变量
var dispatchSource : dispatch_source_t! // MARK: 初始化
override init() { super.init()
dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, , , dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ))
} init(inQueue : GCDQueue) { super.init()
self.dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, , , inQueue.dispatchQueue)
} // MARK: 执行
func event(block : dispatch_block_t, timeIntervalWithNanoseconds : UInt64) { dispatch_source_set_timer(dispatchSource, dispatch_time(DISPATCH_TIME_NOW, ), timeIntervalWithNanoseconds, ) dispatch_source_set_event_handler(dispatchSource) { () -> Void in block()
}
} func event(block : dispatch_block_t, timeIntervalWithSeconds : Double) { let timeInterval : UInt64 = UInt64(timeIntervalWithSeconds * Double(NSEC_PER_SEC))
dispatch_source_set_timer(dispatchSource, dispatch_time(DISPATCH_TIME_NOW, ), timeInterval, )
dispatch_source_set_event_handler(dispatchSource) { () -> Void in block()
}
} func start() { dispatch_resume(dispatchSource)
} func destroy() { dispatch_source_cancel(dispatchSource)
}
}
//
// GCDSemaphore.swift
// GCD
//
// http://home.cnblogs.com/u/YouXianMing/
// https://github.com/YouXianMing
//
// Created by YouXianMing on 15/10/9.
// import UIKit class GCDSemaphore: NSObject { // MARK: 变量
var dispatchSemaphore : dispatch_semaphore_t! // MARK: 初始化
override init() { super.init()
dispatchSemaphore = dispatch_semaphore_create()
} init(withValue : Int) { super.init()
dispatchSemaphore = dispatch_semaphore_create(withValue)
} // 执行
func signal() -> Bool { return dispatch_semaphore_signal(dispatchSemaphore) !=
} func wait() { dispatch_semaphore_wait(dispatchSemaphore, DISPATCH_TIME_FOREVER)
} func wait(withNanoseconds : Int64) -> Bool { return dispatch_semaphore_wait(dispatchSemaphore, dispatch_time(DISPATCH_TIME_NOW, withNanoseconds)) ==
}
}
//
// ViewController.swift
// GCD
//
// Created by YouXianMing on 15/10/9.
// Copyright © 2015年 YouXianMing. All rights reserved.
// import UIKit class ViewController: UIViewController { var queue : GCDQueue!
var group : GCDGroup!
var timer : GCDTimer!
var semaphore : GCDSemaphore! override func viewDidLoad() { super.viewDidLoad() timerUse()
} // MARK: 各种用法 /**
普通用法
*/
func normalUse() { GCDQueue.globalQueue.excute { () -> Void in // 子线程执行操作 GCDQueue.mainQueue.excute({ () -> Void in // 主线程更新UI
})
} GCDQueue.executeInGlobalQueue { () -> Void in // 子线程执行操作 GCDQueue.executeInMainQueue({ () -> Void in // 主线程更新UI
})
}
} /**
延时用法
*/
func delayUse() { GCDQueue.executeInGlobalQueue({ () -> Void in // 延时 2s 执行 }, afterDelaySeconds: )
} func waitExecute() { queue = GCDQueue(queueType: .ConcurrentQueue) queue.waitExecute { () -> Void in print("")
sleep()
} queue.waitExecute { () -> Void in print("")
sleep()
} queue.waitExecute { () -> Void in print("")
sleep()
} queue.waitExecute { () -> Void in print("")
}
} /**
设置屏障
*/
func barrierExecute() { queue = GCDQueue(queueType: .ConcurrentQueue) queue.excute { () -> Void in print("")
} queue.excute { () -> Void in print("")
} queue.excute { () -> Void in print("")
sleep()
} queue.barrierExecute { () -> Void in print("barrierExecute")
} queue.excute { () -> Void in print("")
} queue.excute { () -> Void in print("")
} queue.excute { () -> Void in print("")
}
} /**
GCDGroup的使用
*/
func groupUse() { group = GCDGroup()
queue = GCDQueue() queue.excute({ () -> Void in print("") }, inGroup: group) queue.excute({ () -> Void in print("") }, inGroup: group) queue.excute({ () -> Void in print("") }, inGroup: group) queue.excute({ () -> Void in print("") }, inGroup: group) queue.excute({ () -> Void in print("") }, inGroup: group) queue.excute({ () -> Void in print("") }, inGroup: group) queue.excute({ () -> Void in print("") }, inGroup: group) queue.excute({ () -> Void in print("") }, inGroup: group) queue.notify({ () -> Void in print("都完成了") }, inGroup: group)
} /**
GCDTimer的使用
*/
func timerUse() { timer = GCDTimer(inQueue: GCDQueue.globalQueue)
timer.event({ () -> Void in print("timer event") }, timeIntervalWithSeconds: )
timer.start()
} /**
GCD信号量的使用
*/
func semaphoreUse() { semaphore = GCDSemaphore()
queue = GCDQueue(queueType: .ConcurrentQueue) queue.excute { () -> Void in print("")
self.semaphore.signal()
} queue.excute { () -> Void in print("")
self.semaphore.signal()
} queue.excute { () -> Void in print("")
self.semaphore.signal()
} queue.excute { () -> Void in print("")
self.semaphore.signal()
} queue.excute { () -> Void in self.semaphore.wait()
self.semaphore.wait()
self.semaphore.wait()
self.semaphore.wait() print("都完成了")
}
}
}

细节

swift版的GCD封装的更多相关文章

  1. Swift版音乐播放器(简化版),swift音乐播放器

    这几天闲着也是闲着,学习一下Swift的,于是到开源社区Download了个OC版的音乐播放器,练练手,在这里发扬开源精神, 希望对大家有帮助! 这个DEMO里,使用到了 AudioPlayer(对音 ...

  2. Swift版音乐播放器(简化版)

    这几天闲着也是闲着,学习一下Swift的.于是到开源社区Download了个OC版的音乐播放器,练练手,在这里发扬开源精神. 希望对大家有帮助! 这个DEMO里.使用到了 AudioPlayer(对音 ...

  3. GCD封装的个人理解和应用

    GCD封装的个人理解和应用 特点 >>将GCD封装,使我们从繁琐的方法记忆中解脱出来,能够直接快速的应用. 使用方法 1.将工程中的GCD文件中的9个文件拖入自己的工程中(你自己最好建一个 ...

  4. Swift版iOS游戏框架Sprite Kit基础教程下册

    Swift版iOS游戏框架Sprite Kit基础教程下册 试读下载地址:http://pan.baidu.com/s/1qWBdV0C 介绍:本教程是国内唯一的Swift版的Spritekit教程. ...

  5. 快速排序OC、Swift版源码

    前言: 你要问我学学算法在工作当中有什么用,说实话,当达不到那个地步的时候,可能我们不能直接的感觉到它的用处!你就抱着这样一个心态,当一些APP中涉及到算法的时候我不想给其他人画界面!公司的项目也是暂 ...

  6. iOS可视化动态绘制八种排序过程(Swift版)

    前面几篇博客都是关于排序的,在之前陆陆续续发布的博客中,我们先后介绍了冒泡排序.选择排序.插入排序.希尔排序.堆排序.归并排序以及快速排序.俗话说的好,做事儿要善始善终,本篇博客就算是对之前那几篇博客 ...

  7. swift版的CircleView

    swift版的CircleView 效果图 源码 // // CircleView.swift // CircleView // // Created by YouXianMing on 15/10/ ...

  8. swift版的StringAttribute

    swift版的StringAttribute 效果 源码 https://github.com/YouXianMing/Swift-StringAttribute // // StringAttrib ...

  9. swift版的元组

    swift版的元组 说明 元组的内容并不多,使用的话跟普通变量类似,以下是测试源码: // // ViewController.swift // Tuples // // Created by You ...

随机推荐

  1. xgboost 参数

    XGBoost 参数 在运行XGBoost程序之前,必须设置三种类型的参数:通用类型参数(general parameters).booster参数和学习任务参数(task parameters). ...

  2. HTTP协议常用标准状态码含义

     HTTP协议常用标准状态码含义 状态码    含义 备注 200 请求已完成 2XX状态码均为正常状态码返回. 300 多种选择 服务器根据请求可执行多种操作.服务器可根据请求者 (User age ...

  3. ruby中nil?, empty? and blank?的选择

    In Ruby, you check with nil? if an object is nil: article = nil article.nil? # => true empty? che ...

  4. Qt5 编程基础

    Qt 是一个C++ GUI应用框架,Qt 具有良好的可移植性支持大多数桌面和移动操作系统并常用于嵌入式开发. Qt的发行版分为商业版和开源版,提供了Qt Creator作为轻量级IDE. Hello ...

  5. Socket编程 - 网络基础知识

    API编程部分:http://www.cnblogs.com/Jimmy1988/p/7895213.html 1. 协议简介 此处,我们主要介绍Linux编程常用的三种协议(TCP/UDP/IP), ...

  6. IDEA 中将已有项目放到 GitHub 上去

    前言:公司用的都是 idea+svn 来管理代码,所以家里尝试一下 idea+github 来管理.我的本地仓库是配置过ssh key,所以此处没有再次配置ssh key,如需配置可以参考 https ...

  7. github 上如何直接预览仓库中的html,搭建自己的主页

    前言:最近在写vue+element ui 的一些demo,就在github上建了个仓库来管理,但是希望能直接在github上就能预览效果,所以才有了这篇文章.转载请注明出处:https://www. ...

  8. SSH下shiro的基本使用

    1.引入依赖 <!-- 权限控制 框架 -->
 <dependency>
 <groupId>org.apache.shiro</groupId>
 ...

  9. SQL0286N 找不到页大小至少为 "8192"、许可使用授权标识 "db2inst" 的缺省表空间。

    在 SQL 处理期间,它返回: SQL0286N  找不到页大小至少为 "8192".许可使用授权标识 "db2inst" 的缺省表空间. 顾名思义,DB2默认 ...

  10. Algorithm——Add Two Numbers(补上周)

    一.question You are given two non-empty linked lists representing two non-negative integers. The digi ...