Created
March 16, 2013 23:32
-
-
Save davidgrenier/5178813 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System | |
type Message= | |
| GetToken of AsyncReplyChannel<IDisposable> | |
| Release | |
let start count = | |
let agent = | |
MailboxProcessor.Start(fun inbox -> | |
let token = | |
{ new IDisposable with | |
member x.Dispose () = inbox.Post Release } | |
let release = function | |
| Release -> Some (async.Return Release) | |
| _ -> None | |
let rec loop = function | |
| 0 -> async { | |
let! _ = inbox.Scan release | |
return! loop 1 | |
} | |
| n -> async { | |
let! msg = inbox.Receive () | |
return! | |
match msg with | |
| Release -> loop (n + 1) | |
| GetToken port -> port.Reply token; loop (n - 1) | |
} | |
loop count) | |
fun () -> agent.PostAndAsyncReply GetToken | |
let getToken = start 100; | |
for x = 0 to 1000 do | |
async { | |
use! token = getToken() | |
let sleepTime = x % 10 * 100 + 500 | |
Console.WriteLine (sprintf "%d Sleeping for %d..." x sleepTime) | |
do! Async.Sleep sleepTime | |
Console.WriteLine (sprintf "%d Releasing..." x) | |
} |> Async.Start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment