about summary refs log blame commit diff stats
path: root/channel.mu
blob: 66d0be7966820897cb50feb62ef6cbdf82b5d7be (plain) (tree)
1
2
3
4
5
6
7
8
9
# example program: communicating between routines using channels

def producer sink:&:sink:char -> sink:&:sink:char [
  # produce characters 1 to 5 on a channel
  local-scope
  load-ingredients
  # n = 0
  n:char <- copy 0
  {
    done?:bool <- lesser-than n, 5
    break-unless done?
    # other threads might get between these prints
    $print [produce: ], n, [ 
]
    sink <- write sink, n
    n <- add n, 1
    loop
  }
  close sink
]

def consumer source:&:source:char -> source:&:source:char [
  # consume and print integers from a channel
  local-scope
  load-ingredients
  {
    # read an integer from the channel
    n:char, eof?:bool, source <- read source
    break-if eof?
    # other threads might get between these prints
    $print [consume: ], n:char, [ 
]
    loop
  }
]

def main [
  local-scope
  source:&:source:char, sink:&:sink:char <- new-channel 3/capacity
  # create two background 'routines' that communicate by a channel
  routine1:num <- start-running producer, sink
  routine2:num <- start-running consumer, source
  wait-for-routine routine1
  wait-for-routine routine2
]
"> current_instruction().to_string() << '\n' << end(); break; } if (Current_scenario) break; // do nothing in tests string filename; if (is_literal_string(current_instruction().ingredients.at(0))) { filename = current_instruction().ingredients.at(0).name; } else if (is_mu_string(current_instruction().ingredients.at(0))) { filename = read_mu_string(ingredients.at(0).at(0)); } else { raise << current_recipe_name() << ": first ingredient of 'save' should be a string, but got " << current_instruction().ingredients.at(0).to_string() << '\n' << end(); break; } if (!scalar(ingredients.at(1))) { raise << current_recipe_name() << ": second ingredient of 'save' should be an address:array:character, but got " << current_instruction().ingredients.at(1).to_string() << '\n' << end(); break; } ofstream fout(("lesson/"+filename).c_str()); string contents = read_mu_string(ingredients.at(1).at(0)); fout << contents; fout.close(); if (!exists("lesson/.git")) break; // bug in git: git diff -q messes up --exit-code // explicitly say '--all' for git 1.9 int status = system("cd lesson; git add --all .; git diff HEAD --exit-code >/dev/null || git commit -a -m . >/dev/null"); if (status != 0) raise << "error in commit: contents " << contents << '\n' << end(); break; } :(code) bool exists(const string& filename) { struct stat dummy; return 0 == stat(filename.c_str(), &dummy); } :(before "End Includes") #include<sys/stat.h>