Giter Site home page Giter Site logo

semaphore's Introduction

Semaphore

A Synchronization Primitive for Swift Concurrency

Requirements: iOS 13.0+ / macOS 10.15+ / tvOS 13.0+ / watchOS 6.0+ โ€ข Swift 5.10+ / Xcode 15.3+

๐Ÿ“– Documentation


This package provides AsyncSemaphore, a traditional counting semaphore.

Unlike DispatchSemaphore, it does not block any thread. Instead, Swift concurrency tasks are suspended "awaiting" for the semaphore.

Usage

You can use a semaphore to suspend a task and resume it later:

let semaphore = AsyncSemaphore(value: 0)

Task {
  // Suspends the task until a signal occurs.
  await semaphore.wait()
  await doSomething()
}

// Resumes the suspended task.
semaphore.signal()

An actor can use a semaphore so that its methods can't run concurrently, avoiding the "actor reentrancy problem":

actor MyActor {
  private let semaphore = AsyncSemaphore(value: 1)
  
  func serializedMethod() async {
    // Makes sure no two tasks can execute
    // serializedMethod() concurrently. 
    await semaphore.wait()
    defer { semaphore.signal() }
    
    await doSomething()
    await doSomethingElse()
  }
}

A semaphore can generally limit the number of concurrent accesses to a resource:

class Downloader {
  private let semaphore: AsyncSemaphore

  /// Creates a Downloader that can run at most
  /// `maxDownloadCount` concurrent downloads. 
  init(maxDownloadCount: Int) {
    semaphore = AsyncSemaphore(value: maxDownloadCount) 
  }

  func download(...) async throws -> Data {
    try await semaphore.waitUnlessCancelled()
    defer { semaphore.signal() }
    return try await ...
  }
}

You can see in the latest example that the wait() method has a waitUnlessCancelled variant that throws CancellationError if the task is cancelled before a signal occurs.

For a nice introduction to semaphores, see The Beauty of Semaphores in Swift ๐Ÿšฆ. The article discusses DispatchSemaphore, but it can easily be ported to Swift concurrency: get inspiration from the above examples.

semaphore's People

Contributors

gregcotten avatar groue avatar tayloraswift avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

semaphore's Issues

Unexpected deadlock with AsyncStream

Hey there, thanks for sharing this excellent library! I'm sorry to say I'm running into an unexpected deadlock where my AsyncStream's onTermination handler doesn't execute while I'm waiting for the semaphore. Here's a brief demo of the problem as a playground:

Screenshot 2024-08-12 at 4 54 46โ€ฏPM

Above code as gist

Please let me know if there's anything I can clarify to help debug

Discussion: Safety of using NS(Recursive)Lock across awaits

Thank you for open sourcing this approach. I don't have a real issue, but wanted to share some thoughts. There's no discussions tab hence the issue.

I was curious to better understand how this works, because initially I assumed this might not be safe.

I thought locking across awaits is not safe, because locks have to be unlocked on the same thread.

"NSLock can be used safely but require caution to only use in synchronous code and not across an await."

Source: https://forums.swift.org/t/incremental-migration-to-structured-concurrency/54939/21

 public func wait() async {
        lock()
        // ...
        await withUnsafeContinuation { continuation in
            // ...
            unlock()
        }
    }

I wasn't sure if this could deadlock on small machine with a pool size of one, if at the suspension point marked by the await another async wait is run first and then trying to get the lock. Or if the closure would be executed on another thread as with Swift Concurrency there's not much guarantees about the thread on which an async function runs.

I now think this works, because of special behavior of withUnsafeContinuation:

"The closure is then immediately executed in the same execution context (in other words, the current thread) [...]"
Source: https://forums.swift.org/t/clarification-needed-on-unsafecontinuation-documentation/57803/2

If withTaskCancellationHandler and withUnsafeThrowingContinuation also have behave like that it starts to make more sense for me.

Or is there another reason why the locking code works in this case?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.