2015-05-11 19:00:50 +00:00
|
|
|
# example program: communicating between routines using channels
|
|
|
|
|
2016-09-17 19:55:10 +00:00
|
|
|
def producer sink:&:sink:char -> sink:&:sink:char [
|
2015-10-06 01:40:51 +00:00
|
|
|
# produce characters 1 to 5 on a channel
|
2015-07-14 05:43:16 +00:00
|
|
|
local-scope
|
2017-12-04 07:25:40 +00:00
|
|
|
load-inputs
|
2015-05-06 04:17:24 +00:00
|
|
|
# n = 0
|
2016-09-17 07:31:55 +00:00
|
|
|
n:char <- copy 0
|
2015-05-06 04:17:24 +00:00
|
|
|
{
|
2016-10-08 17:52:58 +00:00
|
|
|
done?:bool <- lesser-than n, 5
|
2015-07-29 08:23:22 +00:00
|
|
|
break-unless done?
|
2015-05-06 04:17:24 +00:00
|
|
|
# other threads might get between these prints
|
2015-07-29 08:23:22 +00:00
|
|
|
$print [produce: ], n, [
|
2015-05-06 04:17:24 +00:00
|
|
|
]
|
2016-04-24 18:54:30 +00:00
|
|
|
sink <- write sink, n
|
2015-07-29 08:23:22 +00:00
|
|
|
n <- add n, 1
|
2015-05-06 04:17:24 +00:00
|
|
|
loop
|
2014-11-25 09:25:20 +00:00
|
|
|
}
|
2016-09-12 16:15:59 +00:00
|
|
|
close sink
|
2015-05-06 04:17:24 +00:00
|
|
|
]
|
2014-11-25 09:25:20 +00:00
|
|
|
|
2016-09-17 19:55:10 +00:00
|
|
|
def consumer source:&:source:char -> source:&:source:char [
|
2015-05-06 04:17:24 +00:00
|
|
|
# consume and print integers from a channel
|
2015-07-14 05:43:16 +00:00
|
|
|
local-scope
|
2017-12-04 07:25:40 +00:00
|
|
|
load-inputs
|
2015-05-06 04:17:24 +00:00
|
|
|
{
|
|
|
|
# read an integer from the channel
|
2016-10-08 17:52:58 +00:00
|
|
|
n:char, eof?:bool, source <- read source
|
2016-04-28 05:28:55 +00:00
|
|
|
break-if eof?
|
2015-05-06 04:17:24 +00:00
|
|
|
# other threads might get between these prints
|
2016-09-17 07:31:55 +00:00
|
|
|
$print [consume: ], n:char, [
|
2015-05-06 04:17:24 +00:00
|
|
|
]
|
|
|
|
loop
|
2014-11-25 09:25:20 +00:00
|
|
|
}
|
2015-05-06 04:17:24 +00:00
|
|
|
]
|
2014-11-25 09:25:20 +00:00
|
|
|
|
2016-03-08 09:30:14 +00:00
|
|
|
def main [
|
2015-07-14 05:43:16 +00:00
|
|
|
local-scope
|
2016-09-17 19:55:10 +00:00
|
|
|
source:&:source:char, sink:&:sink:char <- new-channel 3/capacity
|
2015-05-06 04:17:24 +00:00
|
|
|
# create two background 'routines' that communicate by a channel
|
2016-09-17 07:43:13 +00:00
|
|
|
routine1:num <- start-running producer, sink
|
|
|
|
routine2:num <- start-running consumer, source
|
2015-07-29 08:23:22 +00:00
|
|
|
wait-for-routine routine1
|
|
|
|
wait-for-routine routine2
|
2015-05-06 04:17:24 +00:00
|
|
|
]
|