Skip to content

Instantly share code, notes, and snippets.

@duanebester
Created November 19, 2020 01:39
Show Gist options
  • Save duanebester/4594e61526688f716198ec6c31517be1 to your computer and use it in GitHub Desktop.
Save duanebester/4594e61526688f716198ec6c31517be1 to your computer and use it in GitHub Desktop.
Playing with threads in Unison
use .base
use .base.Text
use .base.Nat
counter.doc = [:
@counter takes an `id` parameter and number `n` parameter to be incremented.
Prints id and number: "Counter <id>: <n>".
Recursively calls itself every 3 seconds with an incremented number.
@[signature] counter
:]
counter: Nat -> Nat -> ()
counter id n =
delay (3 * 1000 * 1000) -- ~3 sec
printLine ("Counter " ++ (toText id) ++ ": " ++ (toText n))
counter id (n+1)
buildIds: Nat -> [Text] -> [Text]
buildIds num acc =
if num < 1 then acc
else buildIds (drop num 1) (acc List.++ [(Nat.toText num)])
-- > List.head (buildIds 3 [])
-- test> buildsIds.tests.ex1 = check ((buildIds 0 []) == [])
-- test> buildsIds.tests.ex2 = check ((buildIds 3 []) == ["3","2","1"])
forkCounters: Nat -> [ThreadId] -> [ThreadId]
forkCounters num acc =
if num < 1 then acc
else
tid = fork '(counter num 0)
printLine ("New Counter Thread -- " ++ (match tid with ThreadId t -> t))
forkCounters (drop num 1) (acc List.++ [tid])
release: [ThreadId] -> ()
release threadIds =
match (List.head threadIds) with Some tid ->
kill tid
printLine ("Stopped thread -- " ++ (match tid with ThreadId t -> t))
match (List.tail threadIds) with
Some ts -> release ts
what: [ThreadId] -> ()
what threadIds =
printLine ("What received " ++ (toText (List.size threadIds)) ++ " thread ids!")
printLine ("What waiting for input...")
-- Just block on any input...
cmd = !readLine
printLine cmd
main : '{io.IO} ()
main = 'let
acquire = '(forkCounters 2 [])
bracket acquire release what
printLine "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment