Last active
October 29, 2016 14:44
-
-
Save roehst/e98a9b0703ceb75d85f7b212b60005ee to your computer and use it in GitHub Desktop.
Parallel boolean functions in Elixir
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Parbool do | |
require Process | |
def or_(task1, task2) do | |
parent = self | |
pid1 = spawn(fn -> send parent, task1.() end) | |
pid2 = spawn(fn -> send parent, task2.() end) | |
receive do | |
false -> | |
receive do | |
result2 -> | |
Process.exit pid1, :kill | |
Process.exit pid2, :kill | |
result2 | |
end | |
true -> | |
Process.exit pid1, :kill | |
Process.exit pid2, :kill | |
true | |
end | |
end | |
def and_(task1, task2) do | |
parent = self | |
pid1 = spawn(fn -> send parent, task1.() end) | |
pid2 = spawn(fn -> send parent, task2.() end) | |
receive do | |
true -> | |
receive do | |
result2 -> | |
Process.exit pid1, :kill | |
Process.exit pid2, :kill | |
result2 | |
end | |
false -> | |
Process.exit pid1, :kill | |
Process.exit pid2, :kill | |
false | |
end | |
end | |
def xor_(task1, task2) do | |
parent = self | |
pid1 = spawn(fn -> send parent, task1.() end) | |
pid2 = spawn(fn -> send parent, task2.() end) | |
receive do | |
result1 -> | |
receive do | |
result2 -> | |
Process.exit pid1, :kill | |
Process.exit pid2, :kill | |
(result2 or result1) and not (result1 and result2) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This small module provides an implementation of
or
andand
in parallel and using short-circuit evaluation. It can shutdown the remaining computation if the first one returns and short-circuits the operator.