[erlang-questions] spawn race condition?

Bob Ippolito bob@REDACTED
Tue Apr 3 19:52:23 CEST 2007


On 4/3/07, Anthony Shipman <als@REDACTED> wrote:
> I have code that looks like this:
>
> call(Phone) ->
>     Pid = spawn(?MODULE, init, [Phone]),
>
>     util:delay(100),
>     Pid! {startCall, self()},
>     receive
>         callComplete -> {ok, Pid}
>     after
>         5000 -> false
>     end.
>
> If I don't have the 100ms delay then the only message that the new process
> receives is the integer 0. It works with the delay. Am I missing something?

spawn is async. You should have it message back on startup to notify
that it's running, that way you can make it sync. Surely OTP does this
somewhere.. but it'd look something like this:

spawn_sync(Fun) ->
    Self = self(),
    F = fun () ->
        Self ! {started, self()},
        Fun()
    end,
    Pid = spawn(F),
    receive
        {started, Pid} ->
            Pid;
    after 5000 ->
        error
    end.



More information about the erlang-questions mailing list