Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
13 changes: 13 additions & 0 deletions Sources/Foundation/NSLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,19 @@ public protocol NSLocking {
func unlock()
}

extension NSLocking {
@_alwaysEmitIntoClient
@_disfavoredOverload
public func withLock<R>(_ body: () throws -> R) rethrows -> R {
self.lock()
defer {
self.unlock()
}

return try body()
}
}

#if os(Windows)
private typealias _MutexPointer = UnsafeMutablePointer<SRWLOCK>
private typealias _RecursiveMutexPointer = UnsafeMutablePointer<CRITICAL_SECTION>
Expand Down
30 changes: 30 additions & 0 deletions Tests/Foundation/Tests/TestNSLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class TestNSLock: XCTestCase {
("test_lockWait", test_lockWait),
("test_threadsAndLocks", test_threadsAndLocks),
("test_recursiveLock", test_recursiveLock),
("test_withLock", test_withLock),

]
}
Expand Down Expand Up @@ -187,4 +188,33 @@ class TestNSLock: XCTestCase {

threadCompletedCondition.unlock()
}

func test_withLock() {
let lock = NSLock()

var counter = 0
let counterIncrementPerThread = 10_000

let threadCount = 10

let threadCompletedExpectation = expectation(description: "Expected threads to complete.")
threadCompletedExpectation.expectedFulfillmentCount = threadCount

for _ in 0..<threadCount {
let thread = Thread {
for _ in 0..<counterIncrementPerThread {
lock.withLock {
counter += 1
}
}

threadCompletedExpectation.fulfill()
}
thread.start()
}

wait(for: [threadCompletedExpectation], timeout: 10)

XCTAssertEqual(counter, counterIncrementPerThread * threadCount)
}
}