DBThreadSafe

2.1.0

dodobrands/DBThreadSafe-ios

What's New

2.1.0

2024-01-10T20:51:47Z

What's Changed

New Contributors

Full Changelog: 2.0.0...2.1.0

DBThreadSafeContainer

DBThreadSafeContainer is a generic class that provides thread-safe read and write access to a stored value. It uses a pthread_rwlock_t lock to ensure that multiple threads can safely access the value concurrently.

Usage

Initialization

To create a new instance of DBThreadSafeContainer, simply initialize it with an initial value:

let container = DBThreadSafeContainer("Hello, World!")

Reading the value

To read the value stored in the container, use the read() method:

let value = container.read()

Alternatively, you can pass a closure to the read() method to perform operations on the value within the lock:

container.read { value in
    // Perform read-only operations on the value
}

You can also use the read() method with a closure that returns a value:

let result = container.read { value -> Int in
    // Perform read-only operations on the value and return a result
    return value.count
}

Simplier way:

let result = container.read { $.count }

If you need to handle errors within the closure, you can use the read() method that throws:

try container.read { value in
    // Perform read-only operations on the value that can throw errors
}

Writing the value

To replace the current value with a new one, use the write() method:

container.write("New value")

You can also pass a closure to the write() method to make multiple modifications to the value within the lock:

container.write { value in
    // Make multiple modifications to the value
}

If you need to handle errors within the closure, you can use the write() method that throws:

try container.write { value in
    // Make multiple modifications to the value that can throw errors
}

Thread Safety

DBThreadSafeContainer ensures that read and write operations are thread-safe by using a pthread_rwlock_t lock. This allows multiple threads to read the value concurrently, while ensuring that only one thread can write to the value at a time.

Cleanup

DBThreadSafeContainer automatically destroys the pthread_rwlock_t lock when it is deallocated to prevent any resource leaks.

License

This code is released under the Apache License. See LICENSE for more information.

Description

  • Swift Tools 5.8.0
View More Packages from this Author

Dependencies

  • None
Last updated: Sun May 05 2024 19:53:54 GMT-0900 (Hawaii-Aleutian Daylight Time)