Skip to content

Instantly share code, notes, and snippets.

@shinnya
Forked from eatonphil/thread.ml
Created April 7, 2018 01:15
Show Gist options
  • Save shinnya/164f065c3af38f5b059dc6a6adcd4dee to your computer and use it in GitHub Desktop.
Save shinnya/164f065c3af38f5b059dc6a6adcd4dee 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