Skip to content

Commit

Permalink
add test for computing only once in multithread
Browse files Browse the repository at this point in the history
  • Loading branch information
kazbekovruslan committed May 31, 2024
1 parent 1a956da commit 83eb923
Showing 1 changed file with 11 additions and 13 deletions.
24 changes: 11 additions & 13 deletions Homework7/Lazy.Tests/Tests.fs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ let lazyConstructors =
(fun f -> LockFreeLazy f :> ILazy<obj>) ]
|> List.map (fun f -> TestCaseData(f))

let multiThreadLazyConstructors =
[ (fun f -> ThreadSafeLazy f :> ILazy<obj>)
(fun f -> LockFreeLazy f :> ILazy<obj>) ]
|> List.map (fun f -> TestCaseData(f))

[<TestCaseSource(nameof lazyConstructors)>]
let ``Value should compute only once`` (lazyConstructor: (unit -> obj) -> ILazy<obj>) =
Expand Down Expand Up @@ -48,20 +44,22 @@ let ``Exception in supplier should be thrown`` (lazyConstructor: (unit -> obj) -
let lazyObject = lazyConstructor (fun () -> raise (System.Exception()))
Assert.Throws<System.Exception>(fun () -> lazyObject.Get() |> ignore) |> ignore

[<Test>]
let ``Multithread lazy test`` () =
let counter = ref 0

[<TestCaseSource(nameof multiThreadLazyConstructors)>]
let ``Multithread lazies test`` (lazyConstructor: (unit -> obj) -> ILazy<obj>) =
let supplier () = obj ()

let lazyObject = lazyConstructor supplier
let amountOfThreads = 8
let supplier () =
System.Threading.Interlocked.Increment(counter) |> ignore
obj ()

let tasksArray =
Seq.init amountOfThreads (fun _ -> async { return lazyObject.Get() })
let lazyObject = ThreadSafeLazy supplier :> obj ILazy

tasksArray
Seq.initInfinite (fun _ -> async { return lazyObject.Get() })
|> Seq.take 8
|> Async.Parallel
|> Async.RunSynchronously
|> Seq.distinct
|> Seq.length
|> should equal 1

counter.Value |> should equal 1

0 comments on commit 83eb923

Please sign in to comment.