Created
November 21, 2014 22:09
-
-
Save davidgrenier/1007360badd3186477f1 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
#I @"C:\Projects\Lib" | |
#r "Hopac.dll" | |
#r "Hopac.Core.dll" | |
open System | |
open Hopac | |
open Hopac.Job.Infixes | |
open Hopac.Alt.Infixes | |
open Hopac.Extensions | |
let get n = | |
Ch.create() >>= (fun output -> | |
Ch.create() >>= (fun input -> | |
Ch.create() >>= (fun count -> | |
let disposable = | |
{ | |
new IDisposable with | |
member __.Dispose() = Ch.give input () |> run | |
} | |
Job.iterateServer n (function | |
| 0 -> | |
printfn "No more tokens" | |
Ch.take input >>% 1 | |
| n -> | |
printfn "Still have %d tokens" n | |
Alt.select [ | |
Ch.Alt.take input >>%? (n + 1) | |
Ch.Alt.give output disposable >>%? (n - 1) | |
Ch.Alt.give count n >>%? n | |
] | |
) | |
) | |
) | |
>>% Ch.take output | |
) | |
job { | |
let! limiter = get 5 | |
do! | |
job { | |
printfn "Getting token" | |
use! token = limiter | |
printfn "Got token" | |
do! Timer.Global.sleep <| TimeSpan.FromSeconds 3.0 | |
printfn "Releasing token" | |
} | |
|> Job.start | |
|> Job.forN 100 | |
} | |
|> run | |
async { | |
use! token = Async.Global.ofJob limiter | |
printfn "Got token" | |
do! Async.Sleep 3000 | |
printfn "Releasing token" | |
} | |
|> Async.Start |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment