Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- open System
- open System.Threading
- open System.Diagnostics
- let lock (elem : int ref) value =
- Monitor.Enter(elem);
- try
- if value > elem.Value then elem := value
- finally
- Monitor.Exit(elem)
- let searchMaxInRange (arr:int[]) l r :int =
- let mutable res = Int32.MinValue
- for x=l to r do
- if arr.[x]>res then res <- arr.[x]
- res
- let searchMax (arr:int[], threadNumber:int) =
- let length = arr.Length
- let res = ref arr.[0]
- let step = length / threadNumber
- let threadArray = Array.init threadNumber (fun i ->
- new Thread(ThreadStart(fun _ ->
- let threadRes = searchMaxInRange arr (i * step) ((i+1) * step - 1)
- lock res threadRes
- )))
- for t in threadArray do
- t.Start()
- for t in threadArray do
- t.Join()
- if (threadNumber*step < length) then
- lock res (searchMaxInRange arr (threadNumber*step)(length-1))
- printfn "%A" res.Value
- [<EntryPoint>]
- let main argv =
- let timer = new System.Diagnostics.Stopwatch()
- timer.Start()
- let n = 10000000
- let arr = Array.init n (fun i -> System.Random(0).Next(0, n))
- searchMax (arr, 1)
- printfn "%i" timer.ElapsedMilliseconds
- 0 // return an integer exit code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement