Pool is Sendable

This commit is contained in:
Gwendal Roué committed 2024-07-27 16:37:33 +02:00
1 parent 57a86a0e2a
commit f13b2d2eb4
4 files changed
+46 -35

No files matched your search

+2 -4
View File
@@ -62,17 +62,15 @@ public final class DatabasePool {
// an opened transaction.
readerConfiguration.allowsUnsafeTransactions = false
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [readerConfiguration] index in
return try SerializedDatabase(
path: path,
configuration: readerConfiguration,
defaultLabel: "GRDB.DatabasePool",
purpose: "reader.\(readerCount)")
purpose: "reader.\(index)")
})
// Set up journal mode unless readonly
+8 -11
View File
@@ -130,6 +130,7 @@ public final class DatabaseSnapshotPool {
/// `db` is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs.
public init(_ db: Database, configuration: Configuration? = nil) throws {
let path = db.path
var configuration = Self.configure(configuration ?? db.configuration)
// Acquire and hold WAL snapshot
@@ -138,7 +139,7 @@ public final class DatabaseSnapshotPool {
}
var holderConfig = Configuration()
holderConfig.allowsUnsafeTransactions = true
snapshotHolder = try DatabaseQueue(path: db.path, configuration: holderConfig)
snapshotHolder = try DatabaseQueue(path: path, configuration: holderConfig)
try snapshotHolder.inDatabase { db in
try db.beginTransaction(.deferred)
try db.execute(sql: "SELECT rootpage FROM sqlite_master LIMIT 1")
@@ -158,20 +159,18 @@ public final class DatabaseSnapshotPool {
}
self.configuration = configuration
self.path = db.path
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: db.path,
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
@@ -219,17 +218,15 @@ public final class DatabaseSnapshotPool {
self.path = path
self.walSnapshot = walSnapshot
var readerCount = 0
readerPool = Pool(
maximumCount: configuration.maximumReaderCount,
qos: configuration.readQoS,
makeElement: {
readerCount += 1 // protected by Pool (TODO: document this protection behavior)
makeElement: { [configuration] index in
return try SerializedDatabase(
path: path,
configuration: configuration,
defaultLabel: "GRDB.DatabaseSnapshotPool",
purpose: "snapshot.\(readerCount)")
purpose: "snapshot.\(index)")
})
}
+33 -19
View File
@@ -35,8 +35,9 @@ import Dispatch
/// got 2
/// got 1
/// got 3
final class Pool<T> {
private class Item {
final class Pool<T: Sendable>: Sendable {
private class Item: @unchecked Sendable {
// @unchecked because `isAvailable` is protected by `content`.
let element: T
var isAvailable: Bool
@@ -46,8 +47,19 @@ final class Pool<T> {
}
}
private let makeElement: () throws -> T
@ReadWriteBox private var items: [Item] = []
private struct Content {
var items: [Item]
/// The number of created items. May become greater than the number
/// of elements in items, as some items are destroyed and other
/// are created.
var createdCount = 0
}
typealias ElementAndRelease = (element: T, release: @Sendable (PoolCompletion) -> Void)
private let makeElement: @Sendable (Int) throws -> T
private let content = ReadWriteBox(wrappedValue: Content(items: [], createdCount: 0))
private let itemsSemaphore: DispatchSemaphore // limits the number of elements
private let itemsGroup: DispatchGroup // knows when no element is used
private let barrierQueue: DispatchQueue
@@ -59,11 +71,12 @@ final class Pool<T> {
/// - maximumCount: The maximum number of elements.
/// - qos: The quality of service of asynchronous accesses.
/// - makeElement: A function that creates an element. It is called
/// on demand.
/// on demand. Its argument is the index of the created elements
/// (1, then 2, etc).
init(
maximumCount: Int,
qos: DispatchQoS = .unspecified,
makeElement: @escaping () throws -> T)
makeElement: @escaping @Sendable (_ index: Int) throws -> T)
{
GRDBPrecondition(maximumCount > 0, "Pool size must be at least 1")
self.makeElement = makeElement
@@ -75,19 +88,20 @@ final class Pool<T> {
/// Returns a tuple (element, release)
/// Client must call release(), only once, after the element has been used.
func get() throws -> (element: T, release: (PoolCompletion) -> Void) {
func get() throws -> ElementAndRelease {
try barrierQueue.sync {
itemsSemaphore.wait()
itemsGroup.enter()
do {
let item = try $items.update { items -> Item in
if let item = items.first(where: \.isAvailable) {
let item = try content.update { content -> Item in
if let item = content.items.first(where: \.isAvailable) {
item.isAvailable = false
return item
} else {
let element = try makeElement()
content.createdCount += 1
let element = try makeElement(content.createdCount)
let item = Item(element: element, isAvailable: false)
items.append(item)
content.items.append(item)
return item
}
}
@@ -107,7 +121,7 @@ final class Pool<T> {
///
/// - important: The `execute` argument is executed in a serial dispatch
/// queue, so make sure you use the element asynchronously.
func asyncGet(_ execute: @escaping (Result<(element: T, release: (PoolCompletion) -> Void), Error>) -> Void) {
func asyncGet(_ execute: @escaping @Sendable (Result<ElementAndRelease, Error>) -> Void) {
// Inspired by https://khanlou.com/2016/04/the-GCD-handbook/
// > We wait on the semaphore in the serial queue, which means that
// > we’ll have at most one blocked thread when we reach maximum
@@ -128,7 +142,7 @@ final class Pool<T> {
}
private func release(_ item: Item, completion: PoolCompletion) {
$items.update { items in
content.update { content in
switch completion {
case .reuse:
// This is why Item is a class, not a struct: so that we can
@@ -136,8 +150,8 @@ final class Pool<T> {
item.isAvailable = true
case .discard:
// Discard should be rare: perform lookup.
if let index = items.firstIndex(where: { $0 === item }) {
items.remove(at: index)
if let index = content.items.firstIndex(where: { $0 === item }) {
content.items.remove(at: index)
}
}
}
@@ -148,8 +162,8 @@ final class Pool<T> {
/// Performs a block on each pool element, available or not.
/// The block is run is some arbitrary dispatch queue.
func forEach(_ body: (T) throws -> Void) rethrows {
try $items.read { items in
for item in items {
try content.read { content in
for item in content.items {
try body(item.element)
}
}
@@ -158,7 +172,7 @@ final class Pool<T> {
/// Removes all elements from the pool.
/// Currently used elements won't be reused.
func removeAll() {
items = []
content.update { $0.items.removeAll() }
}
/// Blocks until no element is used, and runs the `barrier` function before
@@ -172,7 +186,7 @@ final class Pool<T> {
/// Asynchronously runs the `barrier` function when no element is used, and
/// before any other element is dequeued.
func asyncBarrier(execute barrier: @escaping () -> Void) {
func asyncBarrier(execute barrier: @escaping @Sendable () -> Void) {
barrierQueue.async(flags: [.barrier]) {
self.itemsGroup.wait()
barrier()
+3 -1
View File
@@ -5,7 +5,9 @@ class PoolTests: XCTestCase {
/// Returns a Pool whose elements are incremented integers: 1, 2, 3...
private func makeCounterPool(maximumCount: Int) -> Pool<Int> {
let count = ReadWriteBox(wrappedValue: 0)
return Pool(maximumCount: maximumCount, makeElement: count.increment)
return Pool(maximumCount: maximumCount, makeElement: { _ in
count.increment()
})
}
func testElementsAreReused() throws {