From f13b2d2eb421e6eab57c81bd1b603ea0527d3c10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 11 Feb 2024 11:52:45 +0100 Subject: [PATCH] Pool is Sendable --- GRDB/Core/DatabasePool.swift | 6 ++-- GRDB/Core/DatabaseSnapshotPool.swift | 19 +++++----- GRDB/Utils/Pool.swift | 52 ++++++++++++++++++---------- Tests/GRDBTests/PoolTests.swift | 4 ++- 4 files changed, 46 insertions(+), 35 deletions(-) diff --git a/GRDB/Core/DatabasePool.swift b/GRDB/Core/DatabasePool.swift index 778cbf8d3..dfaf1e143 100644 --- a/GRDB/Core/DatabasePool.swift +++ b/GRDB/Core/DatabasePool.swift @@ -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 diff --git a/GRDB/Core/DatabaseSnapshotPool.swift b/GRDB/Core/DatabaseSnapshotPool.swift index 7927eb89d..703374b95 100644 --- a/GRDB/Core/DatabaseSnapshotPool.swift +++ b/GRDB/Core/DatabaseSnapshotPool.swift @@ -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)") }) } diff --git a/GRDB/Utils/Pool.swift b/GRDB/Utils/Pool.swift index 6e1014c75..2e993717f 100644 --- a/GRDB/Utils/Pool.swift +++ b/GRDB/Utils/Pool.swift @@ -35,8 +35,9 @@ import Dispatch /// got 2 /// got 1 /// got 3 -final class Pool { - private class Item { +final class Pool: 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 { } } - 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 { /// - 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 { /// 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 { /// /// - 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) -> 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 { } 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 { 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 { /// 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 { /// 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 { /// 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() diff --git a/Tests/GRDBTests/PoolTests.swift b/Tests/GRDBTests/PoolTests.swift index 29c8fcaf7..dbce4868b 100644 --- a/Tests/GRDBTests/PoolTests.swift +++ b/Tests/GRDBTests/PoolTests.swift @@ -5,7 +5,9 @@ class PoolTests: XCTestCase { /// Returns a Pool whose elements are incremented integers: 1, 2, 3... private func makeCounterPool(maximumCount: Int) -> Pool { let count = ReadWriteBox(wrappedValue: 0) - return Pool(maximumCount: maximumCount, makeElement: count.increment) + return Pool(maximumCount: maximumCount, makeElement: { _ in + count.increment() + }) } func testElementsAreReused() throws {