Skip to content

Instantly share code, notes, and snippets.

@eatonphil
Last active April 7, 2018 01:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eatonphil/3f6a3be6c011949388f4 to your computer and use it in GitHub Desktop.
Save eatonphil/3f6a3be6c011949388f4 to your computer and use it in GitHub Desktop.
Basic thread logic based on condition variables in Poly/ML
(*
* Tested in Poly/ML. To compile: `polyc thread.ml && ./a.out`
*
* Heavily influenced by: http://pages.cs.wisc.edu/~remzi/OSTEP/threads-cv.pdf
* Poly/ML Thread documentation here: http://www.polyml.org/documentation/Reference/Threads.html
* Poly/ML Thread implementation here: https://github.com/polyml/polyml/blob/master/basis/Thread.sml
*)
val done = ref false;
val m = Thread.Mutex.mutex();
val c = Thread.ConditionVar.conditionVar();
fun quit() = let in
Thread.Mutex.lock(m);
done := true;
Thread.ConditionVar.signal(c);
Thread.Mutex.unlock(m) end;
fun join() = let in
Thread.Mutex.lock(m);
while !done = false do let in
Thread.ConditionVar.wait(c, m) end;
Thread.Mutex.unlock(m) end;
fun child() = let in
print "child\n";
quit() end;
fun main() = let in
print "parent start\n";
Thread.Thread.fork(child, []);
join();
print "parent end\n" end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment