# Mu - channel.mu

     1 # example program: communicating between routines using channels
     2
     3 def producer sink:&:sink:char -> sink:&:sink:char [
     4   # produce characters 1 to 5 on a channel
     5   local-scope
     6   load-inputs
     7   # n = 0
     8   n:char <- copy 0
     9   {
    10     done?:bool <- lesser-than n, 5
    11     break-unless done?
    12     # other threads might get between these prints
    13     $print [produce: ], n, [
    14 ]
    15     sink <- write sink, n
    16     n <- add n, 1
    17     loop
    18   }
    19   close sink
    20 ]
    21
    22 def consumer source:&:source:char -> source:&:source:char [
    23   # consume and print integers from a channel
    24   local-scope
    25   load-inputs
    26   {
    27     # read an integer from the channel
    28     n:char, eof?:bool, source <- read source
    29     break-if eof?
    30     # other threads might get between these prints
    31     $print [consume: ], n:char, [
    32 ]
    33     loop
    34   }
    35 ]
    36
    37 def main [
    38   local-scope
    39   source:&:source:char, sink:&:sink:char <- new-channel 3/capacity
    40   # create two background 'routines' that communicate by a channel
    41   routine1:num <- start-running producer, sink
    42   routine2:num <- start-running consumer, source
    43   wait-for-routine routine1
    44   wait-for-routine routine2
    45 ]