Advertisement
Guest User

Untitled

a guest
May 10th, 2015
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.19 KB | None | 0 0
  1. open System
  2. open System.Threading
  3. open System.Diagnostics
  4.  
  5. let lock (elem : int ref) value =
  6.   Monitor.Enter(elem);
  7.    try
  8.     if value > elem.Value then elem := value
  9.       finally
  10.        Monitor.Exit(elem)  
  11.  
  12. let searchMaxInRange (arr:int[]) l r :int =
  13.   let mutable res = Int32.MinValue
  14.   for x=l to r do
  15.    if arr.[x]>res then res <- arr.[x]
  16.   res
  17.  
  18. let searchMax (arr:int[], threadNumber:int) =
  19.   let length = arr.Length
  20.   let res = ref arr.[0]
  21.   let step = length / threadNumber
  22.   let threadArray = Array.init threadNumber (fun i ->
  23.       new Thread(ThreadStart(fun _ ->
  24.           let threadRes = searchMaxInRange arr (i * step) ((i+1) * step - 1)
  25.           lock res threadRes
  26.           )))
  27.   for t in threadArray do
  28.     t.Start()
  29.   for t in threadArray do
  30.     t.Join()
  31.   if (threadNumber*step < length) then
  32.    lock res (searchMaxInRange arr (threadNumber*step)(length-1))
  33.   printfn "%A" res.Value
  34.  
  35.  
  36. [<EntryPoint>]
  37. let main argv =
  38.  let timer = new System.Diagnostics.Stopwatch()
  39.  timer.Start()
  40.  let n = 10000000
  41.  let arr = Array.init n (fun i -> System.Random(0).Next(0, n))
  42.  searchMax (arr, 1)
  43.  printfn "%i" timer.ElapsedMilliseconds
  44.  0 // return an integer exit code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement