Skip to content

Commit

Permalink
fix 1; broken withLock
Browse files Browse the repository at this point in the history
  • Loading branch information
mattmassicotte committed Aug 21, 2024
1 parent 29b5d57 commit 8bb7901
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 10 deletions.
2 changes: 2 additions & 0 deletions Sources/Lock/AsyncLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ public final class AsyncLock {
isolation: isolated (any Actor)? = #isolation,
_ block: @isolated(any) () async throws -> T
) async rethrows -> T {
await lock()

do {
let value = try await block()

Expand Down
36 changes: 27 additions & 9 deletions Tests/LockTests/LockTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@ actor ReentrantActor {
var value = 42
let lock = AsyncLock()

// func doThing() async {
// await lock.withLock {
// try! #require(self.value == 42)
// self.value = 0
// try! await Task.sleep(nanoseconds: 1_000_000)
// try! #require(self.value == 0)
// self.value = 42
// }
// }
func doThingWithLock() async {
await lock.withLock {
try! #require(self.value == 42)
self.value = 0
try! await Task.sleep(nanoseconds: 1_000_000)
try! #require(self.value == 0)
self.value = 42
}
}

func doThing() async {
await lock.lock()
Expand Down Expand Up @@ -53,4 +53,22 @@ struct LockTests {
await task.value
}
}

@Test
func serializesWithLock() async {
let actor = ReentrantActor()
var tasks = [Task<Void, Never>]()

for _ in 0..<1000 {
let task = Task {
await actor.doThingWithLock()
}

tasks.append(task)
}

for task in tasks {
await task.value
}
}
}
2 changes: 1 addition & 1 deletion Tests/LockTests/RecursiveLockTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ struct RecursiveLockTests {
}

@Test
func serializes() async {
func serializesWithRecursiveLock() async {
let actor = RecursiveReentrantActor()
var tasks = [Task<Void, Never>]()

Expand Down

0 comments on commit 8bb7901

Please sign in to comment.