Created
February 9, 2023 21:55
-
-
Save peheje/233b8258d10bb5fc62069064a141bccb to your computer and use it in GitHub Desktop.
Wrap the dotnet thread pool with a Go inspired "waitgroup"
This file contains hidden or 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.Threading | |
type WorkerGroup = | |
{ wait: unit -> unit | |
release: unit -> unit | |
waitGroup: unit -> unit } | |
let initWorkerGroup count = | |
let semaphore = new SemaphoreSlim(count) | |
{ wait = fun () -> semaphore.Wait() | |
release = fun () -> semaphore.Release() |> ignore | |
waitGroup = | |
fun () -> | |
for _ in 1..count do | |
semaphore.Wait() } | |
let queueWork workerGroup data action = | |
workerGroup.wait () | |
let actionCallback _ = | |
try | |
action data | |
finally | |
workerGroup.release () | |
ThreadPool.QueueUserWorkItem(actionCallback, data) |> ignore | |
printfn "Starting" | |
let workers = 50 | |
let workerGroup = initWorkerGroup workers | |
for i in 1..workers do | |
queueWork workerGroup i (fun data -> | |
Thread.Sleep 1000 | |
printfn "Thread %i: had worker-number %i" (Thread.GetCurrentProcessorId()) data) | |
workerGroup.waitGroup () | |
printfn "Main done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment