Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fix concurrency-safety of _ExecutionContext
  • Loading branch information
lorentey committed May 21, 2025
commit 5c7f4e9ac9dad13d24d1e6242cac2f9d0c712467
6 changes: 1 addition & 5 deletions Sources/CollectionsBenchmark/Benchmark/Benchmark.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ public struct Benchmark {
public let title: String
internal var _tasks: _SimpleOrderedDictionary<String, AnyTask> = [:]
internal var _inputGenerators: [_TypeBox: (Int) -> Any] = [:]
private let _executionContext = _ExecutionContext.shared

public init(title: String = "") {
self.title = title
_setUpExecutionCheck()
registerInputGenerator(for: Int.self) { size in
size
}
Expand Down Expand Up @@ -56,10 +56,6 @@ public struct Benchmark {
}
}

internal func _markAsExecuted() {
_executionContext._hasExecuted = true
}

public func allTaskNames() -> [String] {
_tasks.map { $0.key }
}
Expand Down
28 changes: 19 additions & 9 deletions Sources/CollectionsBenchmark/Benchmark/_ExecutionContext.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,38 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2021 - 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//

import Foundation
import Foundation // for atexit
import Synchronization

let _hasDoneSetup: Atomic<Bool> = .init(false)
let _hasExecuted: Atomic<Bool> = .init(false)

private func _exitHandler() {
if !_ExecutionContext.shared._hasExecuted {
if !_hasExecuted.load(ordering: .acquiring) {
fatalError("Did you forget to call Benchmark.start()?")
}
}

internal class _ExecutionContext {
var _hasExecuted = false

private init() {
internal func _setUpExecutionCheck() {
let (exchanged, _) = _hasDoneSetup.compareExchange(
expected: false, desired: true, ordering: .acquiringAndReleasing)
if exchanged {
// Check that Benchmark.start() was executed before exiting the process.
// FIXME: Calling convention mismatch
atexit(_exitHandler)
}

static let shared: _ExecutionContext = { _ExecutionContext() }()
}

internal func _markAsExecuted() {
guard _hasDoneSetup.load(ordering: .acquiring) else {
fatalError("Internal error: _markAsExecuted called before _setUpExecutionCheck")
}
_hasExecuted.store(true, ordering: .releasing)
}