swift版的GCD封装

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, 0)

        return instance
        }()

    static let highPriorityGlobalQueue : GCDQueue = {

        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)

        return instance
        }()

    static let lowPriorityGlobalQueue : GCDQueue = {

        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)

        return instance
        }()

    static let backgroundPriorityGlobalQueue : GCDQueue = {

        let instance           = GCDQueue(queueType: .None)
        instance.dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)

        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)) == 0
    }
}
//
//  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, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0))
    }

    init(inQueue : GCDQueue) {

        super.init()
        self.dispatchSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, inQueue.dispatchQueue)
    }

    // MARK: 执行
    func event(block : dispatch_block_t, timeIntervalWithNanoseconds : UInt64) {

        dispatch_source_set_timer(dispatchSource, dispatch_time(DISPATCH_TIME_NOW, 0), timeIntervalWithNanoseconds, 0)

        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, 0), timeInterval, 0)
        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(0)
    }

    init(withValue : Int) {

        super.init()
        dispatchSemaphore = dispatch_semaphore_create(withValue)
    }

    // 执行
    func signal() -> Bool {

        return dispatch_semaphore_signal(dispatchSemaphore) != 0
    }

    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)) == 0
    }
}
//
//  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: 2)
    }

    func waitExecute() {

        queue = GCDQueue(queueType: .ConcurrentQueue)

        queue.waitExecute { () -> Void in

            print("1")
            sleep(1)
        }

        queue.waitExecute { () -> Void in

            print("2")
            sleep(1)
        }

        queue.waitExecute { () -> Void in

            print("3")
            sleep(1)
        }

        queue.waitExecute { () -> Void in

            print("4")
        }
    }

    /**
    设置屏障
    */
    func barrierExecute() {

        queue = GCDQueue(queueType: .ConcurrentQueue)

        queue.excute { () -> Void in

            print("1")
        }

        queue.excute { () -> Void in

            print("2")
        }

        queue.excute { () -> Void in

            print("3")
            sleep(1)
        }

        queue.barrierExecute { () -> Void in

            print("barrierExecute")
        }

        queue.excute { () -> Void in

            print("4")
        }

        queue.excute { () -> Void in

            print("5")
        }

        queue.excute { () -> Void in

            print("6")
        }
    }

    /**
    GCDGroup的使用
    */
    func groupUse() {

        group = GCDGroup()
        queue = GCDQueue()

        queue.excute({ () -> Void in

            print("1")

            }, inGroup: group)

        queue.excute({ () -> Void in

            print("2")

            }, inGroup: group)

        queue.excute({ () -> Void in

            print("3")

            }, inGroup: group)

        queue.excute({ () -> Void in

            print("4")

            }, inGroup: group)

        queue.excute({ () -> Void in

            print("5")

            }, inGroup: group)

        queue.excute({ () -> Void in

            print("6")

            }, inGroup: group)

        queue.excute({ () -> Void in

            print("7")

            }, inGroup: group)

        queue.excute({ () -> Void in

            print("8")

            }, 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: 1)
        timer.start()
    }

    /**
    GCD信号量的使用
    */
    func semaphoreUse() {

        semaphore = GCDSemaphore()
        queue     = GCDQueue(queueType: .ConcurrentQueue)

        queue.excute { () -> Void in

            print("1")
            self.semaphore.signal()
        }

        queue.excute { () -> Void in

            print("2")
            self.semaphore.signal()
        }

        queue.excute { () -> Void in

            print("3")
            self.semaphore.signal()
        }

        queue.excute { () -> Void in

            print("4")
            self.semaphore.signal()
        }

        queue.excute { () -> Void in

            self.semaphore.wait()
            self.semaphore.wait()
            self.semaphore.wait()
            self.semaphore.wait()

            print("都完成了")
        }
    }
}

细节

时间: 2024-10-06 11:32:36

swift版的GCD封装的相关文章

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

这几天闲着也是闲着,学习一下Swift的,于是到开源社区Download了个OC版的音乐播放器,练练手,在这里发扬开源精神, 希望对大家有帮助! 这个DEMO里,使用到了 AudioPlayer(对音频封装的库) FreeStreamer(老外写的音频高效处理库) LKDBHelper(将数据模型直接写到数据库中的库) AFNetworking (网络库) SDWebImage (图片获取库) 另外,我也把OC版的ProgressHUD转成了Swift版本的HYBProgressHUD,希望对大

swift版的枚举变量

swift版的枚举变量  swift的枚举类型跟普通的类是极为类似的,使用的时候,请不要以为他是一个常量,以下是测试用源码 // // ViewController.swift // SwiftEnum // // Created by YouXianMing on 15/10/9. // Copyright 2015年 ZiPeiYi. All rights reserved. // import UIKit enum Planet: Int { case Mercury = 1, Venus

iOS开发swift版异步加载网络图片(带缓存和缺省图片)

iOS开发之swift版异步加载网络图片     与SDWebImage异步加载网络图片的功能相似,只是代码比较简单,功能没有SD的完善与强大,支持缺省添加图片,支持本地缓存.      异步加载图片的核心代码如下: ? 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 5

swift版的CircleView

swift版的CircleView   效果图 源码 // // CircleView.swift // CircleView // // Created by YouXianMing on 15/10/7. // Copyright 2015年 YouXianMing. All rights reserved. // import UIKit class CircleView: UIView { // MARK: - 变量 var lineWidth : CGFloat = 1 var lin

swift版的StringAttribute

swift版的StringAttribute   效果   源码 https://github.com/YouXianMing/Swift-StringAttribute // // StringAttributeProtocol.swift // Swift-StringAttribute // // Created by YouXianMing on 15/10/8. // Copyright 2015年 YouXianMing. All rights reserved. // import

关东升的iOS实战系列图书 《iOS实战:入门与提高卷(Swift版)》已经上市

                     承蒙广大读者的厚爱我的 <iOS实战:入门与提高卷(Swift版)>京东上市了,欢迎广大读者提出宝贵意见.http://item.jd.com/11766718.html 欢迎关注关东升新浪微博@tony_关东升. 关注智捷课堂微信公共平台,了解最新技术文章.图书.教程信息 更多精品iOS.Cocos.移动设计课程请关注智捷课堂官方网站:http://www.zhijieketang.com智捷课堂论坛网站:http://51work6.com/f

关东升的《iOS实战:图形图像、动画和多媒体卷(Swift版)》上市了

    关东升的<iOS实战:图形图像.动画和多媒体卷(Swift版)>上市了        承蒙广大读者的厚爱我的<iOS实战:图形图像.动画和多媒体卷(Swift版)>京东上市了,欢迎广大读者提出宝贵意见..http://item.jd.com/11760249.html 欢迎关注关东升新浪微博@tony_关东升. 关注智捷课堂微信公共平台,了解最新技术文章.图书.教程信息 更多精品iOS.Cocos.移动设计课程请关注智捷课堂官方网站:http://www.zhijieket

关东升的iOS实战系列图书 《iOS实战:传感器卷(Swift版)》已经上市

         承蒙广大读者的厚爱我的 <iOS实战:传感器卷(Swift版)>京东上市了,欢迎广大读者提出宝贵意见.http://item.jd.com/11760248.html   欢迎关注关东升新浪微博@tony_关东升. 关注智捷课堂微信公共平台,了解最新技术文章.图书.教程信息 更多精品iOS.Cocos.移动设计课程请关注智捷课堂官方网站:http://www.zhijieketang.com智捷课堂论坛网站:http://51work6.com/forum.php

融云在移动端获取token(swift)版

融云在移动端不提供注册, 说是不安全等等原因, 需要在服务器端注册, 然后返回给客户端,但是我们又没有服务器, 因此我们可以用手机模拟服务器发送请求, 这样我们就可以自己注册和登录, 做一个聊天的小应用了. 按照官方文档一步一步来就可以了 本来是在网上找的代码, 麻蛋, 总是401错误,401错误是请求成功了但是参数有问题, 很多代码都写得有问题, 定义的变量不用,该有的变量没写,算了,不吐槽了.上代码 func getToken() { // 申请时必要的参数 let parameters =