l3nz
Hello,
I have been playing with a pmap (parallel map) implementation, for a task that seems easy: to run a series of functions in parallel and gather their results. The “snag” is that I want to handle errors and timeouts out of a given deadline, all of them returning a results and not aborting the general computation or - worse - killing the parent.
I ended up with something like:
def parallel_map_ordered(enum, myFn, errorFn, timeout) do
myWrappedFn = fn v ->
try do
myFn.(v)
rescue
err ->
with Logger.error(
"Crashed pmap: #{Tools.ii(err)} on #{Tools.ii(__STACKTRACE__)} for input #{Tools.ii(v)}"
) do
errorFn.(v, err)
end
end
end
tasks = Enum.map(enum, &Task.async(fn -> myWrappedFn.(&1) end))
Task.yield_many(tasks, timeout)
|> Enum.zip(enum)
|> Enum.map(fn {{%Task{}, res}, orgval} ->
case res do
{:ok, v} ->
v
nil ->
with Logger.error("Timed out pmap: for input #{Tools.ii(orgval)}") do
errorFn.(orgval, :timeout)
end
end
end)
end
That you use by passing two functions:
- one is the main function; it gets called for any element of the Enum and is supposed to return an element
- one is the error handler, that gets called with the value that was supposed to be processed and the error or the kw
:timeout, and returns a value to be inserted into the resulting collection
There is a maximum timeout, after which all computations are aborted.
You use it like this:
test "simplex" do
fnOk = fn v ->
Process.sleep(v * 100)
v * 100
end
fnErr = fn v, e ->
{:error, v, e}
end
assert [100, 200, 300, 100, 200, 100, 200, 500, 100] =
PsTools.parallel_map_ordered(
[1, 2, 3, 1, 2, 1, 2, 5, 1],
fnOk,
fnErr,
5000
)
end
This will work; if you set one of the values to (say) 500, the function will time out and terminate in 5 seconds, but all intermediate values will be preserved.
The implementaion is naive, meaning that there is no batching and everything will be run in parallel, so if you have a file reader and run one million in parallel, you will exhaust file descriptors. If you batch, every batch will be limited by the slowest operation, so again it is kind of meh. But it’s a start.
Now for my questions:
- is there something that I overlooked in the handling? should i catch
:exitin the rescue clause? - was there a simple way to do that using the Tasks module?
TIA
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #blog-post
- #elixir-ls
- #ai
- #elixirconf-us
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 1 to 6- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
Sorc96
Is there a reason why
Task.async_streamwould not work? It seems to support all the things you’ve mentioned.dimitarvp
Including returning errors, yep.
dimitarvp
Basically you can get away with just this:
So more or less: have an executor function where you can neatly take care of exceptions or any special cases before handing off to
ensure_ok_or_error_tuple/1(NOTE: I have not added a catch-all clause there and this is intentional; IMO you’d want the code to crash if you receive an unexpected result so you can add an extra clause to take care of it and not silently ignore it or reshape it into an error tuple that’s not informative; basically: don’t mask a potential bug).Also depending on your scenario you might want these tasks supervised but the docs cover these cases well so I will not repeat them.
l3nz
I tried that before my solution, but I had not seen
on_timeout: :kill_taskoption, so it would abort the whole computation on timeout. Thank you!dimitarvp
Happens to the best of us, sometimes you just need a second pair of eyes for the final touches. And you seem to have done almost all of this already, so good job!
rhcarvalho
I wrote a small helper today which I eventually named
async_map, a constrained version ofTask.Supervisor.async_stream, if you will.It converts timeouts into errors so that I have a single place to handle errors in
post_func. It also givespost_functhe original input, be it for logging or generating a fallback value.I know about the
:zip_input_on_exitoption toTask.Supervisor.async_stream, but the advantage of doing it like this is that I have access to the input in every case of sucess/error/timeout.Example usage: