Skip to content

Instantly share code, notes, and snippets.

@peheje
Created February 9, 2023 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peheje/233b8258d10bb5fc62069064a141bccb to your computer and use it in GitHub Desktop.
Save peheje/233b8258d10bb5fc62069064a141bccb to your computer and use it in GitHub Desktop.
Wrap the dotnet thread pool with a Go inspired "waitgroup"
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