Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add thread safety unit test for LazyCache #318

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 2 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
46 changes: 34 additions & 12 deletions Tests/TSCBasicTests/LazyCacheTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,19 @@ import XCTest
import TSCBasic

class LazyCacheTests: XCTestCase {
func testBasics() {
class Foo {
var numCalls = 0

var bar: Int { return barCache.getValue(self) }
var barCache = LazyCache<Foo, Int>(someExpensiveMethod)
func someExpensiveMethod() -> Int {
numCalls += 1
return 42
}

private class Foo {
var numCalls = 0

var bar: Int { return barCache.getValue(self) }
var barCache = LazyCache<Foo, Int>(someExpensiveMethod)
func someExpensiveMethod() -> Int {
numCalls += 1
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is this thread safe?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think so. The someExpensiveMethod() is protected by a lock. Maybe LazyCache should be named something like ThreadSafeLazyCache?

return 42
}

// FIXME: Make this a more interesting test once we have concurrency primitives.
}

func testBasics() {
for _ in 0..<10 {
let foo = Foo()
XCTAssertEqual(foo.numCalls, 0)
Expand All @@ -36,4 +35,27 @@ class LazyCacheTests: XCTestCase {
}
}
}

func testThreadSafety() {
let dispatchGroup = DispatchGroup()
let exp = expectation(description: "multi thread")
for _ in 0..<10 {
let foo = Foo()
for _ in 0..<10 {
dispatchGroup.enter()
DispatchQueue.global().async {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pass the group to the queue method instead of manually enter/leave

XCTAssertEqual(foo.bar, 42)
dispatchGroup.leave()

XCTAssertEqual(foo.numCalls, 1)
}
}
}

dispatchGroup.notify(queue: .main) {
exp.fulfill()
}

wait(for: [exp], timeout: 0.2)
}
}