// Learn more about F# at http://fsharp.net
namespace JQD
type Downloader() =
let ParallelWorker n f =
MailboxProcessor.Start( fun inbox->
let workers =
Array.init n ( fun i ->MailboxProcessor.Start(f))
let rec loop i = async {
let! msg=inbox.Receive()
workers.[i].Post(msg)
return! loop( (i+1)%n)
} loop 0
)
let agent =
ParallelWorker 8,
(fun input ->
let rec loop() = async {
do! Async.Sleep(5000)
return! loop()
}
loop()
)
member this.DowloadAll()=
ParallelWorker 8, (fun data ->
let rec loop() = async {
do! Async.Sleep(5000)
return! loop()
}
loop()
)
Monday, May 31, 2010
F# Parallelism using Agent
F# barebone Agent
Agent = using message passing to avoid mutating state
type Downloader() =
let agent =
MailboxProcessor.Start(fun inbox ->
let rec loop() = async {
let msg=inbox.Receive()
do! Async.Sleep(5000)
return! loop()
}
loop()
)
member this.DowloadAll()=
while(true) do
agent.Post("test")
Barebone F# Parallel programming
open System
let prog(i)=
async {
printfn "starting..%d" i
do! Async.Sleep(i%5*1000)
printfn "finished..%d" i
}
let ret=
[1..1000]
|> Seq.map ( fun n->prog(n))
|> Async.Parallel
|> Async.StartAsTask
Console.ReadLine() |> ignore
F# Parallelism: Map=>Parallel=>StartAsTask
Key ---- function called in Map must have async { }
namespace JQD
type Downloader() =
let Download n=
async {
let f=System.IO.File.ReadLines("")
return f
}
member this.DA()=
[|1.100|]
|> Seq.map(fun n->Download n)
|> Async.Parallel
|> Async.StartAsTask
F# Map Reduce
let nums =[|1..100|]
let sqr x = x*x
let sumofsqr nums =
let mutable acc=0
for n in nums do
acc<-acc+sqr n
acc
let rec sumofsqrRec nums=
match nums with
| []-> 0
| n::rest -> (sqr n)+ (sumofsqrRec rest )
let rec sumofsqrPipe nums=
nums
|>Seq.map sqr
|>Seq.sum
Sunday, May 30, 2010
F# Asyn
F# is sensitive to indentation and linage (e.g. the calling "Donwload" [next line] ()
// Learn more about F# at http://fsharp.net
namespace JQD
type Downloader() =
let folder="test"
let Download()=
async {
let f=System.IO.File.ReadLines("")
let g="456"
return f
}
member this.DA()=
async {
while(true) do
let n=Download
()
}
|>Async.StartImmediate
Subscribe to:
Posts (Atom)