https://github.com/grype/rwlock-swift
Read-Write lock in Swift
https://github.com/grype/rwlock-swift
concurrency lock pthreads readwritelock swift
Last synced: 3 months ago
JSON representation
Read-Write lock in Swift
- Host: GitHub
- URL: https://github.com/grype/rwlock-swift
- Owner: grype
- License: mit
- Created: 2021-04-11T05:38:48.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2021-04-11T06:27:33.000Z (about 4 years ago)
- Last Synced: 2024-04-24T11:24:57.144Z (about 1 year ago)
- Topics: concurrency, lock, pthreads, readwritelock, swift
- Language: Swift
- Homepage:
- Size: 4.88 KB
- Stars: 1
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# RWLock
Swift wrapper around pthread_rwlock.
See [Read-Write Lock](https://en.wikipedia.org/wiki/Readers–writer_lock) for details.
Usage:
```swift
let lock = RWLock()
lock.readProtected {
// do something concurrently with other reads and until write lock is acquired
}
lock.writeProtected {
// do something that requires exclusive access
}
```Using propety wrapper:
```swift
class Foo {
@RWLocked var items = [Any]()
func add(_ item: Any) {
items.append(item)
}
func removeAll() {
items.removeAll()
}
func iterate() {
items.forEach {
// do something with each item
}
}
}
```Any modifications to `items` array will require write protection - this applies to methods `add(_:)` and `removeAll()`. In contrast, `iterate()`ing over the array requires read access. This means that you won't be able to `add(_:)` or `removeAll()` until iteration is complete, and you won't be able to `iterate()` until `add(_:)` or `removeAll()` had finished.