Skip to content

Instantly share code, notes, and snippets.

@roehst
Last active October 29, 2016 14:44
Show Gist options
  • Save roehst/e98a9b0703ceb75d85f7b212b60005ee to your computer and use it in GitHub Desktop.
Save roehst/e98a9b0703ceb75d85f7b212b60005ee to your computer and use it in GitHub Desktop.
Parallel boolean functions in Elixir
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
@roehst
Copy link
Author

roehst commented Oct 29, 2016

This small module provides an implementation of or and and in parallel and using short-circuit evaluation. It can shutdown the remaining computation if the first one returns and short-circuits the operator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment