Type-safe thread-local storage in Swift

Overview

Threadly

Threadly is a Swift µframework that allows for type-safe thread-local storage.

What is Thread-Local Storage?

Thread-local storage (TLS) lets you define a single variable that each thread has its own separate copy of. This is great for cases such as having a mutable global variable that can't be safely accessed by multiple threads.

One example of this is with random number generators. Each thread can have its own seeded generator that's mutated on a per-thread basis. While this may potentially use more memory, it's much faster than accessing a shared global variable through a mutex.

Build Status

Branch Status
master Build Status

Installation

Compatibility

  • Platforms:
    • macOS 10.9+
    • iOS 8.0+
    • watchOS 2.0+
    • tvOS 9.0+
    • Linux
  • Xcode 8.0+
  • Swift 3.0+

Install Using Swift Package Manager

The Swift Package Manager is a decentralized dependency manager for Swift.

  1. Add the project to your Package.swift.

    import PackageDescription
    
    let package = Package(
        name: "MyAwesomeProject",
        dependencies: [
            .Package(url: "https://github.com/nvzqz/Threadly.git",
                     majorVersion: 1)
        ]
    )
  2. Import the Threadly module.

    import Threadly

Install Using CocoaPods

CocoaPods is a centralized dependency manager for Objective-C and Swift. Go here to learn more.

  1. Add the project to your Podfile.

    use_frameworks!
    
    pod 'Threadly', '~> 2.0.1'

    If you want to be on the bleeding edge, replace the last line with:

    pod 'Threadly', :git => 'https://github.com/nvzqz/Threadly.git'
  2. Run pod install and open the .xcworkspace file to launch Xcode.

  3. Import the Threadly framework.

    import Threadly

Install Using Carthage

Carthage is a decentralized dependency manager for Objective-C and Swift.

  1. Add the project to your Cartfile.

    github "nvzqz/Threadly"
    
  2. Run carthage update and follow the additional steps in order to add Threadly to your project.

  3. Import the Threadly framework.

    import Threadly

Install Manually

Simply add Threadly.swift into your project.

Usage

Try it out for yourself! Download the repo and open 'Threadly.playground'.

Initialization

There are two ways to initialize a thread-local value. The value can be initialized lazily when retrieved (init(value:) & init(create:)) or at the call site (init(capturing:)).

Using init(value:) is an @autoclosure shorthand for init(create:). This means that the thread-local value is initialized once per thread.

import Foundation

let array = ThreadLocal(value: [1, 2, 3])

Thread.detachNewThread {
    // Allocates an array with 3 elements for this thread
    let arr = array.inner.value
    doStuff(with: arr)
}

// Allocates another array of 3 elements for the main thread
doStuff(with: array.inner.value)

When using init(capturing:), the thread-local value is initialized at the call site.

import Foundation

// The inner value gets allocated
let array = ThreadLocal(capturing: [1, 2, 3])

Thread.detachNewThread {
    // Retrieves a shallow copy of the initial value that can be used in this
    // thread. If the thread-local value gets mutated, a deep copy occurs to
    // retain value semantics.
    let arr = array.inner.value
    doStuff(with: arr)
}

// Same as the other thread, but now in the main thread
doStuff(with: array.inner.value)

Exclusivity

Each thread has exclusive access to its own local variable.

import Foundation

let num = ThreadLocal(value: 42)

Thread.detachNewThread {
    withUnsafePointer(to: &num.inner.value) { ptr in
        print(ptr) // 0x00007fa6f86074a0
    }
}

withUnsafePointer(to: &num.inner.value) { ptr in
    print(ptr) // 0x00007fa6f844c920
}

License

All source code for Threadly is released under the MIT License.

Assets for Threadly are released under the Creative Commons Attribution-ShareAlike 4.0 International License and can be found in the assets branch.

You might also like...
Kommander is a Swift library to manage the task execution in different threads.
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.

SwiftCoroutine - Swift coroutines for iOS, macOS and Linux.
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

Venice - Coroutines, structured concurrency and CSP for Swift on macOS and Linux.
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

Syntactic sugar in Swift for asynchronous dispatches in Grand Central Dispatch

Async Now more than syntactic sugar for asynchronous dispatches in Grand Central Dispatch (GCD) in Swift Async sugar looks like this: Async.userInitia

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 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.

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

 GCDTimer - Well tested Grand Central Dispatch (GCD) Timer in Swift
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

Schedule timing task in Swift using a fluent API. (A friendly alternative to Timer)
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

Grand Central Dispatch simplified with swift.

GCDKit 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 Introductio

Comments
  • Xcode files with xcode9.3

    Xcode files with xcode9.3

    With Xcode9.3, If I change Show checkbox on scheme management window, Xcode make a this file.

    I use this library by gitsubmodule + carthage and add xcodeproj to xcworkspace for application development. So this diff makes work repository state dirty. Please merge this.

    It similar to https://github.com/nvzqz/RandomKit/pull/57 https://github.com/nvzqz/ShiftOperations/pull/1

    By the way, I made this PR for master branch. But your RandomKit points v1.0.0 of Threadly.

    So I want same patch for v1.0.0 actually. But there is a possibility to update Threadly for RandomKit. How do you think?

    opened by omochi 2
Releases(v2.0.1)
  • v2.0.1(Jul 25, 2017)

    Fixes

    • Made withThreadLocal(_:) part of the ThreadLocalRetrievable definition
      • If this method is reimplemented elsewhere, it's not ambiguous to the compiler which version to use
      • Has a default implementation, making this a non-breaking change
    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Jun 26, 2017)

    New Features

    • Added conversions between ThreadLocal and DeferredThreadLocal

    Changes

    • The static threadLcoal value for ThreadLocalRetrievable returns a Box instead of a ThreadLocal
    • Changed internals of ThreadLocal and DeferredThreadLocal, making them struct types instead of class types
    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jun 25, 2017)

  • v1.1.1(Jun 24, 2017)

  • v1.1.0(Jun 23, 2017)

  • v1.0.0(Jun 22, 2017)

Owner
Nikolai Vazquez
conducts curses, breaks things, and uses the oxford comma
Nikolai Vazquez
Type-safe networking with Swift Concurrency

AsyncRequest AsyncRequest is a type-safe framework for building a suite of requests to communicate with an API, built on top of Swift Concurrency. Ins

Light Year Software, LLC 1 Feb 9, 2022
Demonstration of using Tasks and TaskGroup to thread a calculation.

TasksTest Demonstration of using Tasks and TaskGroup to thread a calculation. The calculation takes place in a separate Swift class that can be reused

null 0 Dec 27, 2021
**`withCheckedContinuation`'s body will run on background thread in case of starting from main-actor.**

ConcurrencyContinuationReproduce Differences of Concurrency behaviors between Xcode 14.0 and 14.1 Xcode 14.0 iOS 13+: Runs on main (inherited same con

Hiroshi Kimura 4 Dec 20, 2022
⚡️ Fast async task based Swift framework with focus on type safety, concurrency and multi threading

Our apps constantly do work. The faster you react to user input and produce an output, the more likely is that the user will continue to use your appl

Said Sikira 814 Oct 30, 2022
Type-Erased Existential Generic AsyncSequence Values in Swift

AnyAsyncSequence AnyAsyncSequence allows you to expose AsyncSequence interfaces in your APIs without exposing the underlying sequence type, while cont

Varun Santhanam 9 Nov 23, 2022
A general purpose embedded hierarchical lock manager used to build highly concurrent applications of all types. Same type of locker used in many of the large and small DBMSs in existence today.

StickyLocking StickyLocking is a general purpose embedded lock manager which allows for locking any resource hierarchy. Installable Lock modes allow f

Sticky Tools 2 Jun 15, 2021
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