Grand Central Dispatch simplified with swift.

Related tags

Concurrency GCDKit
Overview

GCDKit

Build Status Version Platform License Carthage compatible Swift Package Manager compatible

GCDKit is Grand Central Dispatch simplified with Swift.

  • for Swift 1.2: Use version 1.0.1
  • for Swift 2.1 / 2.2: Use the master branch

Introduction

GCDKit implements the following constructs. To see how they work, jump right to the Common Usage Patterns section below.

  • GCDQueue: An abstraction of the dispatch_queue_* API. GCDQueues are expressed as enums, because we typically only need to deal with these queue types:
public enum GCDQueue {
    case Main
    case UserInteractive
    case UserInitiated
    case Default
    case Utility
    case Background
    case Custom(dispatch_queue_t) // serial or concurrent
}
  • GCDBlock: A struct that abstracts iOS 8's new dispatch_block_* family of APIs.
  • GCDGroup: An abstraction of the dispatch_group_* API.
  • GCDSemaphore: An abstraction of the dispatch_semaphore_* API.

Common Usage Patterns

Here are some common use cases and how you can write them using GCDKit.

Creating and initializing queues

With the iOS SDK:

let mainQueue = dispatch_get_main_queue()
let defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let customSerialQueue = dispatch_queue_create("mySerialQueue", DISPATCH_QUEUE_SERIAL)
let customConcurrentQueue = dispatch_queue_create("myConcurrentQueue", DISPATCH_QUEUE_CONCURRENT)

With GCDKit:

let mainQueue: GCDQueue = .Main
let defaultQueue: GCDQueue = .Default
let customSerialQueue: GCDQueue = .createSerial("mySerialQueue")
let customConcurrentQueue: GCDQueue = .createConcurrent("myConcurrentQueue")

In addition, custom queues created with dispatch_queue_create(...) typically target a default-priority global queue unless you use the dispatch_set_target_queue(...) API. For example, to raise the priority level of a created queue with the current SDK:

let customConcurrentQueue = dispatch_queue_create("myConcurrentQueue", DISPATCH_QUEUE_CONCURRENT)
dispatch_set_target_queue(customConcurrentQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0))

With GCDKit, you can immediately specify the target queue on creation:

let customConcurrentQueue: GCDQueue = .createConcurrent("myConcurrentQueue", targetQueue: .UserInteractive)

Submitting tasks to queues

With the iOS SDK:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // some heavy work...
    dispatch_async(dispatch_get_main_queue()) {
        // send results to UI
    }
}

With GCDKit you can either start a task chain from GCDBlock.async(...):

GCDBlock.async(.Default) {
    // some heavy work...
}.notify(.Main) {
    // send results to UI
}

or directly from a specific GCDQueue enum value:

GCDQueue.Default.async {
    // some heavy work...
}.notify(.Main) {
    // send results to UI
}

You can chain .notify(...) calls as much as needed.

Launching and reporting completion of a group of tasks

With the iOS SDK:

let dispatchGroup = dispatch_group_create()

dispatch_group_enter(dispatchGroup)
doSomeLongTaskWithCompletion {
    dispatch_group_leave(dispatchGroup)
}

dispatch_group_async(dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // do another long task
}
dispatch_group_async(dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    // do yet another long task
}

dispatch_group_notify(dispatchGroup, dispatch_get_main_queue()) {
    // report completion
}

With GCDKit you can still use the usual enter()-leave() pairs and you can chain async calls to the dispatch group:

let dispatchGroup = GCDGroup()

dispatchGroup.enter()
doSomeLongTaskWithCompletion {
    dispatchGroup.leave()
}

dispatchGroup.async(.Default) {
    // do another long task
}.async(.Default) {
    // do yet another long task
}.notify(.Main) {
    // report completion
}

Semaphores

With the iOS SDK:

let numberOfIterations: UInt = 10
let semaphore = dispatch_semaphore_create(Int(numberOfIterations))

dispatch_apply(numberOfIterations, dispatch_queue_create("myConcurrentQueue", DISPATCH_QUEUE_CONCURRENT)) {
    (iteration: UInt) -> Void in

    // do work for iteration
    dispatch_semaphore_signal(semaphore)
}

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)

With GCDKit:

let numberOfIterations: UInt = 10
let semaphore = GCDSemaphore(numberOfIterations)

GCDQueue.createConcurrent("myConcurrentQueue").apply(numberOfIterations) {
    (iteration: UInt) -> Void in

    // do work for iteration
    semaphore.signal()
}

semaphore.wait()

Contributions

Feel free to report any issues or send suggestions!

License

GCDKit is released under an MIT license. See the LICENSE file for more information

Comments
  • Change the type of custom queue label from String to optional String

    Change the type of custom queue label from String to optional String

    Hi, @JohnEstropia Thanks for your great lib.

    I changed the type of label of the function that creates custom queue to UnsafePointer, and applied the initial value to nil.

    This changes is based on the following description in the 481-483 lines of dispatch/queue.h:

    * @param label
    * A string label to attach to the queue.
    * This parameter is optional and may be NULL.
    

    But it's OK to close this PR without merge, if you feel not good :bow:

    opened by ra1028 6
  • ITMS-90362 error when using the library and uploading to itunesconnect

    ITMS-90362 error when using the library and uploading to itunesconnect

    The project needs to be updated to have a minimum ios version of 8.0 As a reference, the same issue appeared on Alamofire, here's the link: https://github.com/Alamofire/Alamofire/issues/352 attached is the error from the binary upload

    In the meantime i'll create a fork and update the settings on it.

    Using 1.2.2 version of the lib.

    As i see you have 2 targets on the library, but they build the same framework, overwriting the right one, i'll remove the ios7 target on my fork and build it.

    screen shot 2016-04-30 at 14 13 15

    bug fixed 
    opened by demonar 4
  • EXC_BAD_INSTRUCTION on dispatch_block_notify

    EXC_BAD_INSTRUCTION on dispatch_block_notify

    Im getting an EXC_BAD_INSTRUCTION on GCDBlock.notify when in calls dispatch_block_notify. The calling cod looks like this:

    GCDBlock.async(.Default) {
                ... does she work ...
            }.notify(.Main) {
    
            }
    

    Any idea? (Im using Xcode 7.0.1)

    bug 
    opened by ekampf 4
  • Can't build with xcode 6.4

    Can't build with xcode 6.4

    Hi I am trying to use your latest Pod (GCDKit 1.1.1) but I can't get it to build with Xcode Version 6.4 (6E35b) for iOS 8. I get 63 issues and they seem to be based around @available(iOS, introduced=7.0) Any help would be great.

    opened by jarleif 3
  • Add support for tvOS

    Add support for tvOS

    I did all steps for the project to work as a tvOS framework and tried to apply the same structure as with the other targets. It's building fine for me so I think this can be merged after a short review. Shouldn't break anything.

    opened by Jeehut 2
  • OS X support?

    OS X support?

    Hi John,

    GCDKit is a good library when using swift. I'm just wondering whether it supports osx platform, since the framework that GCDKit needs is Foundation only.

    fixed 
    opened by h1994st 2
  • Is this project being actively developed still?

    Is this project being actively developed still?

    Hi John,

    I really like your GCDKit interfaces. I'd like to make a few initial changes and additions. Add GCD Timer support, etc. We'll probably be making a lot of changes over the long haul that we're using it, but those are the immediate needs right now. I don't want to burden you with change requests, or hi-jack your project, so my options are to either fork it, or adopt it and give it a new name (your name and license to remain intact of course). Do you have any preference on this?

    Thanks!

    Brandon

    opened by bsneed 2
  • Priority support for queues

    Priority support for queues

    Hi,

    can you add support for priorities? At the moment I've to do this:

    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)

    to get a low priority queue.

    With GCDKit in use:

    GCDQueue.Custom(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)).async {}

    but it should be like this:

    GCDQueue.GlobalWithPriority(.LowPrority).async {}

    opened by ext-mki 1
  • GCDQueue `suspend()` and `resume()`

    GCDQueue `suspend()` and `resume()`

    Hey, this PR adds thin wrappers for dispatch_suspend and dispatch_resume to GCDQueue.

    One gotcha with dispatch_suspend is that it must be balanced with a call to dispatch_resume before the queue is deallocated. If we want, we can handle unbalanced suspends for the user with a thin class wrapper for custom queues that tracks suspend count and, on deinit, submits a barrier block to the target queue balancing resumes. Doing so would break clients that keep references to the underlying dispatch queue.

    opened by peyton 1
Owner
John Estropia
John Estropia
GCDTimer - Well tested Grand Central Dispatch (GCD) Timer in Swift

GCDTimer Well tested Grand Central Dispatch (GCD) Timer in Swift. Checkout the test file. Usage Long running timer import GCDTimer

Hemant Sapkota 183 Sep 9, 2022
A wrapper of Grand Central Dispatch written in Swift

GCD A wrapper of Grand Central Dispatch written in Swift. Examples gcd // submit your code for asynchronous execution on a global queue with high prio

Le Van Nghia 75 May 19, 2022
Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch (iOS7+ and OS X 10.9+ compatible)

Async.legacy Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch (GCD) Async rewritten for iOS7 and OS X 10.9 Compatibility

Joseph Lord 31 Jul 1, 2019
Chronos is a collection of useful Grand Central Dispatch utilities

Chronos is a collection of useful Grand Central Dispatch utilities. If you have any specific requests or ideas for new utilities, don't hesitate to create a new issue.

Comyar Zaheri 248 Sep 19, 2022
Queuer is a queue manager, built on top of OperationQueue and Dispatch (aka GCD).

Queuer is a queue manager, built on top of OperationQueue and Dispatch (aka GCD). It allows you to create any asynchronous and synchronous task easily, all managed by a queue, with just a few lines.

Fabrizio Brancati 1k Dec 2, 2022
A complete set of primitives for concurrency and reactive programming on Swift

A complete set of primitives for concurrency and reactive programming on Swift 1.4.0 is the latest and greatest, but only for Swift 4.2 and 5.0 use 1.

AsyncNinja 156 Aug 31, 2022
Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift.

Futures Futures is a cross-platform framework for simplifying asynchronous programming, written in Swift. It's lightweight, fast, and easy to understa

David Ask 60 Aug 11, 2022
GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way

GroupWork is an easy to use Swift framework that helps you orchestrate your concurrent, asynchronous functions in a clean and organized way. This help

Quan Vo 42 Oct 5, 2022
Hydra ⚡️ Lightweight full-featured Promises, Async & Await Library in Swift

Lightweight full-featured Promises, Async & Await Library in Swift What's this? Hydra is full-featured lightweight library which allows you to write b

Daniele Margutti 2k Dec 24, 2022
Kommander is a Swift library to manage the task execution in different threads.

A lightweight, pure-Swift library for manage the task execution in different threads. Through the definition a simple but powerful concept, Kommand.

Intelygenz 173 Apr 11, 2022
SwiftCoroutine - Swift coroutines for iOS, macOS and Linux.

Many languages, such as Kotlin, Go, JavaScript, Python, Rust, C#, C++ and others, already have coroutines support that makes the async/await pattern i

Alex Belozierov 808 Dec 1, 2022
Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.

Venice provides structured concurrency and CSP for Swift. Features Coroutines Coroutine cancelation Coroutine groups Channels Receive-only chan

Zewo 1.5k Dec 22, 2022
AwaitKit is a powerful Swift library which provides a powerful way to write asynchronous code in a sequential manner.

AwaitKit is a powerful Swift library inspired by the Async/Await specification in ES8 (ECMAScript 2017) which provides a powerful way to write asynchronous code in a sequential manner.

Yannick Loriot 752 Dec 5, 2022
Elegant ⏱ interface for Swift apps

Each Elegant ⏱ interface for Swift apps Each is a NSTimer bridge library written in Swift. Features Requirements Installation Usage Leaks License Feat

Luca D'Alberti 764 Dec 29, 2022
Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)

Schedule(简体中文) Schedule is a timing tasks scheduler written in Swift. It allows you run timing tasks with elegant and intuitive syntax. Features Elega

Luo Xiu 1.8k Jan 7, 2023
Queues, timers, and task groups in Swift

Dispatcher eases the pain of using Grand Central Dispatch by introducing 4 new Swift classes. Dispatcher Queue Group Timer Requirements Swift 2.0+ Ins

Alec Larson 109 Jan 29, 2022
A Swift microframework for very easy atomic values.

Atomic Atomic is a fast, safe class for making values thread-safe in Swift. It is backed by pthread_mutex_lock which is the fastest, most-efficient lo

Adlai Holler 36 Sep 26, 2022
⏳ Collection of Swift 5.5 async/await utility functions.

⏳ FunAsync Collection of Swift 5.5 async/await utility functions. Throw <-> Result conversion asyncThrowsToAsyncResult asyncResultToAsyncThrows More C

Yasuhiro Inami 23 Oct 14, 2022
🎭 Swift async/await & Actor-powered effectful state-management framework.

?? Actomaton ??‍?? Actor + ?? Automaton = ?? Actomaton Actomaton is Swift async/await & Actor-powered effectful state-management framework inspired by

Yasuhiro Inami 199 Dec 20, 2022