Last active
November 19, 2020 01:52
-
-
Save duanebester/3177d6623a0634fe3db287ef1767a883 to your computer and use it in GitHub Desktop.
Threads Scratch for Unison
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
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) | |
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