Related
I wanted to send a message to a process after a delay, and discovered erlang:send_after/4.
When looking at the docs it looked like this is exactly what I wanted:
erlang:send_after(Time, Dest, Msg, Options) -> TimerRef
Starts a timer. When the timer expires, the message Msg is sent to the
process identified by Dest.
However, it doesn't seem to work when the destination is running on another node - it tells me one of the arguments are bad.
1> P = spawn('node#host', module, function, [Arg]).
<10585.83.0>
2> erlang:send_after(1000, P, {123}).
** exception error: bad argument
in function erlang:send_after/3
called as erlang:send_after(1000,<10585.83.0>,{123})
Doing the same thing with timer:send_after/3 appears to work fine:
1> P = spawn('node#host', module, function, [Arg]).
<10101.10.0>
2> timer:send_after(1000, P, {123}).
{ok,{-576458842589535,#Ref<0.1843049418.1937244161.31646>}}
And, the docs for timer:send_after/3 state almost the same thing as the erlang version:
send_after(Time, Pid, Message) -> {ok, TRef} | {error, Reason}
Evaluates Pid ! Message after Time milliseconds.
So the question is, why do these two functions, which on the face of it do the same thing, behave differently? Is erlang:send_after broken, or mis-advertised? Or maybe timer:send_after isn't doing what I think it is?
TL;DR
Your assumption is correct: these are intended to do the same thing, but are implemented differently.
Discussion
Things in the timer module such as timer:send_after/2,3 work through the gen_server that defines that as a service. Like any other service, this one can get overloaded if you assign a really huge number of tasks (timers to track) to it.
erlang:send_after/3,4, on the other hand, is a BIF implemented directly within the runtime and therefore have access to system primitives like the hardware timer. If you have a ton of timers this is definitely the way to go. In most programs you won't notice the difference, though.
There is actually a note about this in the Erlang Efficiency Guide:
3.1 Timer Module
Creating timers using erlang:send_after/3 and erlang:start_timer/3 , is much more efficient than using the timers provided by the timer module in STDLIB. The timer module uses a separate process to manage the timers. That process can easily become overloaded if many processes create and cancel timers frequently (especially when using the SMP emulator).
The functions in the timer module that do not manage timers (such as timer:tc/3 or timer:sleep/1), do not call the timer-server process and are therefore harmless.
A workaround
A workaround to gain the efficiency of the BIF without the same-node restriction is to have a process of your own that does nothing but wait for a message to forward to another node:
-module(foo_forward).
-export([send_after/3, cancel/1]).
% Obviously this is an example only. You would want to write this to
% be compliant with proc_lib, write a proper init/N and integrate with
% OTP. Note that this snippet is missing the OTP service functions.
start() ->
spawn(fun() -> loop(self(), [], none) end).
send_after(Time, Dest, Message) ->
erlang:send_after(Time, self(), {forward, Dest, Message}).
loop(Parent, Debug, State) ->
receive
{forward, Dest, Message} ->
Dest ! Message,
loop(Parent, Debug, State);
{system, From, Request} ->
sys:handle_msg(Request, From, Parent, ?MODULE, Debug, State);
Unexpected ->
ok = log(warning, "Received message: ~tp", [Unexpected]),
loop(Parent, Debug, State)
end.
The above example is a bit shallow, but hopefully it expresses the point. It should be possible to get the efficiency of the BIF erlang:send_after/3,4 but still manage to send messages across nodes as well as give you the freedom to cancel a message using erlang:cancel_timer/1
But why?
The puzzle (and bug) is why erlang:send_after/3,4 does not want to work across nodes. The example you provided above looks a bit odd as the first assignment to P was the Pid <10101.10.0>, but the crashed call was reported as <10585.83.0> -- clearly not the same.
For the moment I do not know why erlang:send_after/3,4 doesn't work, but I can say with confidence that the mechanism of operation between the two is not the same. I'll look into it, but I imagine that the BIF version is actually doing some funny business within the runtime to gain efficiency and as a result signalling the target process by directly updating its mailbox instead of actually sending an Erlang message on the higher Erlang-to-Erlang level.
Maybe it is good that we have both, but this should definitely be clearly marked in the docs, and it evidently is not (I just checked).
There is some difference in timeout order if you have many timers.
The example below shows erlang:send_after does not guarantee order, but
timer:send_after does.
1> A = lists:seq(1,10).
[1,2,3,4,5,6,7,8,9,10]
2> [erlang:send_after(100, self(), X) || X <- A].
...
3> flush().
Shell got 2
Shell got 3
Shell got 4
Shell got 5
Shell got 6
Shell got 7
Shell got 8
Shell got 9
Shell got 10
Shell got 1
ok
4> [timer:send_after(100, self(), X) || X <- A].
...
5> flush().
Shell got 1
Shell got 2
Shell got 3
Shell got 4
Shell got 5
Shell got 6
Shell got 7
Shell got 8
Shell got 9
Shell got 10
ok
As my limited (or even wrong) understanding, both Async.StartImmediate and Async.RunSynchronously start an async computation on current thread. Then what is exactly the difference between these two functions? Can anyone help explain?
Update:
After looking into F# source code at https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/control.fs, I think I kind of understand what happens. Async.StartImmediate starts the async on the current thread. After it hits an async binding, whether it will continue to run on the current thread depends on the async binding itself. For example, if the async binding calls Async.SwitchToThreadPool, it will run on ThreadPool instead of the current thread. In this case, you will need to call Async.SwitchToContext if you want to go back to the current thread. Otherwise, if the async binding doesn’t do any switch to other threads, Async.StartImmediate will continue to execute the async binding on the current thread. In this case, there is no need to call Async.SwitchToContext if you simply want to stay on the current thread.
The reason why Dax Fohl’s example works on GUI thread is because Async.Sleep carefully captures
the SynchronizationContext.Current and makes sure the continuation run in the captured context using
SynchronizationContext.Post(). See https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/control.fs#L1631, where unprotectedPrimitiveWithResync wrapper changes the “args.cont” (the continuation)
to be a Post to the captured context (see: https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/control.fs#L1008 — trampolineHolder.Post is basically SynchronizationContext.Post). This will only work
when SynchronizationContext.Current is not null, which is always the case for GUI thread. Especially,
if you run in a console app with StartImmediate, you will find Async.Sleep will indeed go to ThreadPool, because the main thread in console app doesn’t have SynchronizationContext.Current.
So to summarize, this indeed works with GUI thread because certain functions like Async.Sleep, Async.AwaitWaitHandle etc carefully capture and makes sure to post back to the previous context.
It looks this is a deliberate behavior, however this doesn’t seem to be documented anywhere in the MSDN.
Async.RunSynchronously waits until the entire computation is completed. So use this any time you need to run an async computation from regular code and need to wait for the result. Simple enough.
Async.StartImmediate ensures that the computation is run within the current context but doesn't wait until the entire expression is finished. The most common use for this (for me, at least) is when you want to run a computation on the GUI thread, asynchronously. For example if you wanted to do three things on the GUI thread at 1-second intervals, you could write
async {
do! Async.Sleep 1000
doThing1()
do! Async.Sleep 1000
doThing2()
do! Async.Sleep 1000
doThing3()
} |> Async.StartImmediate
That will ensure everything gets called in the GUI thread (assuming you call that from the GUI thread), but won't block the GUI thread for the whole 3 seconds. If you use RunSynchronously there, it'll block the GUI thread for the duration and your screen will become unresponsive.
(If you haven't done GUI programming, then just note that updates to GUI controls all have to be done from the same thread, which can be difficult to coordinate manually; the above takes away a lot of the pain).
To give another example, here:
// Async.StartImmediate
async {
printfn "Running"
do! Async.Sleep 1000
printfn "Finished"
} |> Async.StartImmediate
printfn "Next"
> Running
> Next
// 1 sec later
> Finished
// Async.RunSynchronously
async {
printfn "Running"
do! Async.Sleep 1000
printfn "Finished"
} |> Async.RunSynchronously
printfn "Next"
> Running
// 1 sec later
> Finished
> Next
// Async.Start just for completion:
async {
printfn "Running"
do! Async.Sleep 1000
printfn "Finished"
} |> Async.Start
printfn "Next"
> Next
> Running // With possible race condition since they're two different threads.
// 1 sec later
> Finished
Also note that Async.StartImmediate can't return a value (since it doesn't run to completion before continuing), whereas RunSynchronously can.
If I create a module with this code below
start_nonstop() ->
spawn(fun() ->
Pid = spawn(?MODULE, nonstop, [0]),
timer:sleep(1000),
exit(Pid, kill)
end).
nonstop(N) ->
io:format("number: ~B~n", [N + 1]),
nonstop(N + 1).
and call start_nonstop() from the Erlang shell, I see an endless series of
number: 1
number: 2
...
which means that the nonstop(N) process was not killed as expected by calling exit(Pid,kill)...
What am I doing wrong? Obviously, this code is a mockup, but I think there is always the chance that some logic bug in a process might result in an infinite loop behaviour similar to this one.
I supposed this could be handled by Erlang, but if not, how can I have an Erlang application be protected regarding these kind of situations?
Which patterns of "infinite loops" can Erlang break? For example, if I put a sleep in the middle of the nonstop(N) functions, Erlang can break the infinite loop, but if I put an erlang:yield() it still cannot break from the infinite loop ...
In this case the infinite process is local to the one trying to kill it. But, what if the infinite process was in a different (e.g., remote) Erlang VM? Could it be killed then?
I am a newbie, and I am evaluating Erlang before I put too much effort in learning and using it for serious applications.
Thanks
In this code, you spawn two process.
In function start_nonstop(), you spawn an process, we can call it Process1. Then in Process1, you spawn another process, we call it Process2.
The work of Process2 is:
nonstop(N) ->
io:format("number: ~B~n", [N + 1]),
nonstop(N + 1).
just do io:format("number: ~B~n", [N + 1]), until the Process1 kill it.
In my environment, the Process2 can be killed. But the variable N become very large from the output.
number: 51321
number: 51322
number: 51323
number: 51324
number: 51325
number: 51326
number: 51327
number: 51328
number: 51329
number: 51330
number: 51331
number: 51332
7>
new to Erlang and just having a bit of trouble getting my head around the new paradigm!
OK, so I have this internal function within an OTP gen_server:
my_func() ->
Result = ibrowse:send_req(?ROOTPAGE,[{"User-Agent",?USERAGENT}],get),
case Result of
{ok, "200", _, Xml} -> %<<do some stuff that won't interest you>>
,ok;
{error,{conn_failed,{error,nxdomain}}} -> <<what the heck do I do here?>>
end.
If I leave out the case for handling the connection failed then I get an exit signal propagated to the supervisor and it gets shut down along with the server.
What I want to happen (at least I think this is what I want to happen) is that on a connection failure I'd like to pause and then retry send_req say 10 times and at that point the supervisor can fail.
If I do something ugly like this...
{error,{conn_failed,{error,nxdomain}}} -> stop()
it shuts down the server process and yes, I get to use my (try 10 times within 10 seconds) restart strategy until it fails, which is also the desired result however the return value from the server to the supervisor is 'ok' when I would really like to return {error,error_but_please_dont_fall_over_mr_supervisor}.
I strongly suspect in this scenario that I'm supposed to handle all the business stuff like retrying failed connections within 'my_func' rather than trying to get the process to stop and then having the supervisor restart it in order to try it again.
Question: what is the 'Erlang way' in this scenario ?
I'm new to erlang too.. but how about something like this?
The code is long just because of the comments. My solution (I hope I've understood correctly your question) will receive the maximum number of attempts and then do a tail-recursive call, that will stop by pattern-matching the max number of attempts with the next one. Uses timer:sleep() to pause to simplify things.
%% #doc Instead of having my_func/0, you have
%% my_func/1, so we can "inject" the max number of
%% attempts. This one will call your tail-recursive
%% one
my_func(MaxAttempts) ->
my_func(MaxAttempts, 0).
%% #doc This one will match when the maximum number
%% of attempts have been reached, terminates the
%% tail recursion.
my_func(MaxAttempts, MaxAttempts) ->
{error, too_many_retries};
%% #doc Here's where we do the work, by having
%% an accumulator that is incremented with each
%% failed attempt.
my_func(MaxAttempts, Counter) ->
io:format("Attempt #~B~n", [Counter]),
% Simulating the error here.
Result = {error,{conn_failed,{error,nxdomain}}},
case Result of
{ok, "200", _, Xml} -> ok;
{error,{conn_failed,{error,nxdomain}}} ->
% Wait, then tail-recursive call.
timer:sleep(1000),
my_func(MaxAttempts, Counter + 1)
end.
EDIT: If this code is in a process which is supervised, I think it's better to have a simple_one_for_one, where you can add dinamically whatever workers you need, this is to avoid delaying initialization due to timeouts (in a one_for_one the workers are started in order, and having sleep's at that point will stop the other processes from initializing).
EDIT2: Added an example shell execution:
1> c(my_func).
my_func.erl:26: Warning: variable 'Xml' is unused
{ok,my_func}
2> my_func:my_func(5).
Attempt #0
Attempt #1
Attempt #2
Attempt #3
Attempt #4
{error,too_many_retries}
With 1s delays between each printed message.
I am trying to learn how async and let! work in F#.
All the docs i've read seem confusing.
What's the point of running an async block with Async.RunSynchronously? Is this async or sync? Looks like a contradiction.
The documentation says that Async.StartImmediate runs in the current thread. If it runs in the same thread, it doesn't look very asynchronous to me... Or maybe asyncs are more like coroutines rather than threads. If so, when do they yield back an forth?
Quoting MS docs:
The line of code that uses let! starts the computation, and then the thread is suspended
until the result is available, at which point execution continues.
If the thread waits for the result, why should i use it? Looks like plain old function call.
And what does Async.Parallel do? It receives a sequence of Async<'T>. Why not a sequence of plain functions to be executed in parallel?
I think i'm missing something very basic here. I guess after i understand that, all the documentation and samples will start making sense.
A few things.
First, the difference between
let resp = req.GetResponse()
and
let! resp = req.AsyncGetReponse()
is that for the probably hundreds of milliseconds (an eternity to the CPU) where the web request is 'at sea', the former is using one thread (blocked on I/O), whereas the latter is using zero threads. This is the most common 'win' for async: you can write non-blocking I/O that doesn't waste any threads waiting for hard disks to spin around or network requests to return. (Unlike most other languages, you aren't forced to do inversion of control and factor things into callbacks.)
Second, Async.StartImmediate will start an async on the current thread. A typical use is with a GUI, you have some GUI app that wants to e.g. update the UI (e.g. to say "loading..." somewhere), and then do some background work (load something off disk or whatever), and then return to the foreground UI thread to update the UI when completed ("done!"). StartImmediate enables an async to update the UI at the start of the operation and to capture the SynchronizationContext so that at the end of the operation is can return to the GUI to do a final update of the UI.
Next, Async.RunSynchronously is rarely used (one thesis is that you call it at most once in any app). In the limit, if you wrote your entire program async, then in the "main" method you would call RunSynchronously to run the program and wait for the result (e.g. to print out the result in a console app). This does block a thread, so it is typically only useful at the very 'top' of the async portion of your program, on the boundary back with synch stuff. (The more advanced user may prefer StartWithContinuations - RunSynchronously is kinda the "easy hack" to get from async back to sync.)
Finally, Async.Parallel does fork-join parallelism. You could write a similar function that just takes functions rather than asyncs (like stuff in the TPL), but the typical sweet spot in F# is parallel I/O-bound computations, which are already async objects, so this is the most commonly useful signature. (For CPU-bound parallelism, you could use asyncs, but you could also use TPL just as well.)
The usage of async is to save the number of threads in usage.
See the following example:
let fetchUrlSync url =
let req = WebRequest.Create(Uri url)
use resp = req.GetResponse()
use stream = resp.GetResponseStream()
use reader = new StreamReader(stream)
let contents = reader.ReadToEnd()
contents
let sites = ["http://www.bing.com";
"http://www.google.com";
"http://www.yahoo.com";
"http://www.search.com"]
// execute the fetchUrlSync function in parallel
let pagesSync = sites |> PSeq.map fetchUrlSync |> PSeq.toList
The above code is what you want to do: define a function and execute in parallel. So why do we need async here?
Let's consider something big. E.g. if the number of sites is not 4, but say, 10,000! Then There needs 10,000 threads to run them in parallel, which is a huge resource cost.
While in async:
let fetchUrlAsync url =
async { let req = WebRequest.Create(Uri url)
use! resp = req.AsyncGetResponse()
use stream = resp.GetResponseStream()
use reader = new StreamReader(stream)
let contents = reader.ReadToEnd()
return contents }
let pagesAsync = sites |> Seq.map fetchUrlAsync |> Async.Parallel |> Async.RunSynchronously
When the code is in use! resp = req.AsyncGetResponse(), the current thread is given up and its resource could be used for other purposes. If the response comes back in 1 second, then your thread could use this 1 second to process other stuff. Otherwise the thread is blocked, wasting thread resource for 1 second.
So even your are downloading 10000 web pages in parallel in an asynchronous way, the number of threads are limited to a small number.
I think you are not a .Net/C# programmer. The async tutorial usually assumes that one knows .Net and how to program asynchronous IO in C#(a lot of code). The magic of Async construct in F# is not for parallel. Because simple parallel could be realized by other constructs, e.g. ParallelFor in the .Net parallel extension. However, the asynchronous IO is more complex, as you see the thread gives up its execution, when the IO finishes, the IO needs to wake up its parent thread. This is where async magic is used for: in several lines of concise code, you can do very complex control.
Many good answers here but I thought I take a different angle to the question: How does F#'s async really work?
Unlike async/await in C# F# developers can actually implement their own version of Async. This can be a great way to learn how Async works.
(For the interested the source code to Async can be found here: https://github.com/Microsoft/visualfsharp/blob/fsharp4/src/fsharp/FSharp.Core/control.fs)
As our fundamental building block for our DIY workflows we define:
type DIY<'T> = ('T->unit)->unit
This is a function that accepts another function (called the continuation) that is called when the result of type 'T is ready. This allows DIY<'T> to start a background task without blocking the calling thread. When the result is ready the continuation is called allowing the computation to continue.
The F# Async building block is a bit more complicated as it also includes cancellation and exception continuations but essentially this is it.
In order to support the F# workflow syntax we need to define a computation expression (https://msdn.microsoft.com/en-us/library/dd233182.aspx). While this is a rather advanced F# feature it's also one of the most amazing features of F#. The two most important operations to define are return & bind which are used by F# to combine our DIY<_> building blocks into aggregated DIY<_> building blocks.
adaptTask is used to adapt a Task<'T> into a DIY<'T>.
startChild allows starting several simulatenous DIY<'T>, note that it doesn't start new threads in order to do so but reuses the calling thread.
Without any further ado here's the sample program:
open System
open System.Diagnostics
open System.Threading
open System.Threading.Tasks
// Our Do It Yourself Async workflow is a function accepting a continuation ('T->unit).
// The continuation is called when the result of the workflow is ready.
// This may happen immediately or after awhile, the important thing is that
// we don't block the calling thread which may then continue executing useful code.
type DIY<'T> = ('T->unit)->unit
// In order to support let!, do! and so on we implement a computation expression.
// The two most important operations are returnValue/bind but delay is also generally
// good to implement.
module DIY =
// returnValue is called when devs uses return x in a workflow.
// returnValue passed v immediately to the continuation.
let returnValue (v : 'T) : DIY<'T> =
fun a ->
a v
// bind is called when devs uses let!/do! x in a workflow
// bind binds two DIY workflows together
let bind (t : DIY<'T>) (fu : 'T->DIY<'U>) : DIY<'U> =
fun a ->
let aa tv =
let u = fu tv
u a
t aa
let delay (ft : unit->DIY<'T>) : DIY<'T> =
fun a ->
let t = ft ()
t a
// starts a DIY workflow as a subflow
// The way it works is that the workflow is executed
// which may be a delayed operation. But startChild
// should always complete immediately so in order to
// have something to return it returns a DIY workflow
// postProcess checks if the child has computed a value
// ie rv has some value and if we have computation ready
// to receive the value (rca has some value).
// If this is true invoke ca with v
let startChild (t : DIY<'T>) : DIY<DIY<'T>> =
fun a ->
let l = obj()
let rv = ref None
let rca = ref None
let postProcess () =
match !rv, !rca with
| Some v, Some ca ->
ca v
rv := None
rca := None
| _ , _ -> ()
let receiver v =
lock l <| fun () ->
rv := Some v
postProcess ()
t receiver
let child : DIY<'T> =
fun ca ->
lock l <| fun () ->
rca := Some ca
postProcess ()
a child
let runWithContinuation (t : DIY<'T>) (f : 'T -> unit) : unit =
t f
// Adapts a task as a DIY workflow
let adaptTask (t : Task<'T>) : DIY<'T> =
fun a ->
let action = Action<Task<'T>> (fun t -> a t.Result)
ignore <| t.ContinueWith action
// Because C# generics doesn't allow Task<void> we need to have
// a special overload of for the unit Task.
let adaptUnitTask (t : Task) : DIY<unit> =
fun a ->
let action = Action<Task> (fun t -> a ())
ignore <| t.ContinueWith action
type DIYBuilder() =
member x.Return(v) = returnValue v
member x.Bind(t,fu) = bind t fu
member x.Delay(ft) = delay ft
let diy = DIY.DIYBuilder()
open DIY
[<EntryPoint>]
let main argv =
let delay (ms : int) = adaptUnitTask <| Task.Delay ms
let delayedValue ms v =
diy {
do! delay ms
return v
}
let complete =
diy {
let sw = Stopwatch ()
sw.Start ()
// Since we are executing these tasks concurrently
// the time this takes should be roughly 700ms
let! cd1 = startChild <| delayedValue 100 1
let! cd2 = startChild <| delayedValue 300 2
let! cd3 = startChild <| delayedValue 700 3
let! d1 = cd1
let! d2 = cd2
let! d3 = cd3
sw.Stop ()
return sw.ElapsedMilliseconds,d1,d2,d3
}
printfn "Starting workflow"
runWithContinuation complete (printfn "Result is: %A")
printfn "Waiting for key"
ignore <| Console.ReadKey ()
0
The output of the program should be something like this:
Starting workflow
Waiting for key
Result is: (706L, 1, 2, 3)
When running the program note that Waiting for key is printed immidiately as the Console thread is not blocked from starting workflow. After about 700ms the result is printed.
I hope this was interesting to some F# devs
Lots of great detail in the other answers, but as I beginner I got tripped up by the differences between C# and F#.
F# async blocks are a recipe for how the code should run, not actually an instruction to run it yet.
You build up your recipe, maybe combining with other recipes (e.g. Async.Parallel). Only then do you ask the system to run it, and you can do that on the current thread (e.g. Async.StartImmediate) or on a new task, or various other ways.
So it's a decoupling of what you want to do from who should do it.
The C# model is often called 'Hot Tasks' because the tasks are started for you as part of their definition, vs. the F# 'Cold Task' models.
The idea behind let! and Async.RunSynchronously is that sometimes you have an asynchronous activity that you need the results of before you can continue. For example, the "download a web page" function may not have a synchronous equivalent, so you need some way to run it synchronously. Or if you have an Async.Parallel, you may have hundreds of tasks all happening concurrently, but you want them all to complete before continuing.
As far as I can tell, the reason you would use Async.StartImmediate is that you have some computation that you need to run on the current thread (perhaps a UI thread) without blocking it. Does it use coroutines? I guess you could call it that, although there isn't a general coroutine mechanism in .Net.
So why does Async.Parallel require a sequence of Async<'T>? Probably because it's a way of composing Async<'T> objects. You could easily create your own abstraction that works with just plain functions (or a combination of plain functions and Asyncs, but it would just be a convenience function.
In an async block you can have some synchronous and some async operations, so, for example, you may have a web site that will show the status of the user in several ways, so you may show if they have bills that are due shortly, birthdays coming up and homework due. None of these are in the same database, so your application will make three separate calls. You may want to make the calls in parallel, so that when the slowest one is done, you can put the results together and display it, so, the end result will be that the display is based on the slowest. You don't care about the order that these come back, you just want to know when all three are received.
To finish my example, you may then want to synchronously do the work to create the UI to show this information. So, at the end, you wanted this data fetched and the UI displayed, the parts where order doesn't matter is done in parallel, and where order matters can be done in a synchronous fashion.
You can do these as three threads, but then you have to keep track and unpause the original thread when the third one is finished, but it is more work, it is easier to have the .NET framework take care of this.