# Using semaphores in actor code

**URL:** <https://forums.swift.org/t/using-semaphores-in-actor-code/58301>\
**Category:** Using Swift\
**Tags:** concurrency\
**Created:** [June 20, 2022, 6:48am UTC](https://forums.swift.org/t/using-semaphores-in-actor-code/58301 "2022-06-20T06:48:19Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

**Author:** ![ibex](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ibex/32/30439_2.png) [@ibex](https://forums.swift.org/u/ibex)\
**Post date:** [August 1, 2022, 7:57am UTC](https://forums.swift.org/t/using-semaphores-in-actor-code/58301/3 "2022-08-01T07:57:38Z")

</div>

The following custom semaphore does the work nicely. My **channel actor** no longer deadlocks! 😂

```swift
actor Semaphore {
    private var count: Int
    private var waiters: [CheckedContinuation<Void, Never>] = []

    init(count: Int = 0) {
        self.count = count
    }

    func wait() async {
        count -= 1
        if count >= 0 { return }
        await withCheckedContinuation {
            waiters.append($0)
        }        
    }

    func signal (count: Int = 1) {
        assert(count >= 1)
        self.count += count
        for _ in 0..<count {
            if waiters.isEmpty { return }
            waiters.removeFirst().resume()
        }
    }
}

```

[The [original code](https://forums.swift.org/t/semaphore-alternatives-for-structured-concurrency/59353/3) is by @MarSe32m]

---

_[View the full topic](https://forums.swift.org/t/using-semaphores-in-actor-code/58301)._
