-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasyncParallel.fsx
More file actions
executable file
·64 lines (51 loc) · 1.47 KB
/
asyncParallel.fsx
File metadata and controls
executable file
·64 lines (51 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
open System.Threading
let mutable counter = 0
let mutable lockObj = ref 0
let increase amount = async {
for i in 1 .. amount do
let mutable repeat = true
while repeat do
let init = counter
let value = init + 1
repeat <- init <> Interlocked.CompareExchange(&counter, value, init)
}
let increase' amount =
for i in 1 .. amount do
counter <- counter + 1
let increase'' amount =
for i in 1 .. amount do
lock lockObj (fun () ->
counter <- counter + 1
)
let measure fn =
let sw = System.Diagnostics.Stopwatch.StartNew ()
fn ()
sw.Stop ()
printfn "Time: %A" sw.Elapsed
let main () = async {
printfn "Start 1"
let! s1 = Async.StartChild (increase 100_000_000)
printfn "Start 2"
let! s2 = Async.StartChild (increase 100_000_000)
do! s1
do! s2
printfn "Result: %d" counter
}
let main' () =
let t1 = Thread(ThreadStart(fun () -> increase'' 100_000_000))
let t2 = Thread(ThreadStart(fun () -> increase'' 100_000_000))
t1.Start()
t2.Start()
t1.Join()
t2.Join()
let main'' () = async {
let! s1 = Async.StartChild (async { increase'' 100_000_000 })
let! s2 = Async.StartChild (async { increase'' 100_000_000 })
do! s1
do! s2
printfn "Counter: %d" counter
}
measure (fun () -> Async.RunSynchronously (main ()))
measure (fun () -> increase' 200_000_000)
measure main'
measure (fun () -> Async.RunSynchronously (main'' ()))