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