[erlang-questions] Executing concurrently

Joe Armstrong erlang@REDACTED
Tue Mar 3 17:41:51 CET 2009


On Tue, Mar 3, 2009 at 3:33 PM, ryeguy <ryeguy1@REDACTED> wrote:
> He is saying that he only wants one process to be able to call his fun
> at a time. In the event that 2 processes attempt to execute the fun at
> the same time, one of them will fail while the other one works as
> normal.



Heres a fun:

      F = fun() -> 42 end.

Evaluating F() returns 42

Now spawn two processes

      P1 =  spawn(fun() -> p(F) end),
      P2 =  spawn(fun() -> p(F) end).

here's p(F)

       p(F) ->
             magic:magic(F).

 magic:magic(F) returns 42 or calls exit(ebadArg) if two processes
call magic(F) "at the same time"

 To do this you need a global process called magic, which is started
before you do any of this

  magic:start() -> register(magic, wait()).

   magic:magic(F) ->
           magic ! {eval, self(), F},
           receive
                {magic, Ret} -> Ret
           end.


   wait() ->
       receive
             {eval, Pid, F} ->
                  S = self(),
                  spawn(fun() ->
                                  Pid ! {magic, F()},
                                  Parent ! free
                              end),
                  busy()
      end.

busy() ->
      receive
            {eval, Pid, F} ->
                 exit(Pid, eNotSim),
                 busy();
             free ->
                  wait()
      end.

Or you could send a lock token and evaluate the function locally - all
of this does not seem like good
design.

The Erlang way is to create servers for global operations and send a
sequental stream of
requests to the server, where they are handled in an orderly manner
one at a time.

Cheers

/Joe




>
> On Mar 3, 7:09 am, Andras Georgy Bekes <bek...@REDACTED> wrote:
>> >    I have a function Fun(). If Fun is called simultaneously by two
>> > processes, then it should fail for one process while should succeed
>> > for other. I wrote such function. Now I want to test it! How do I do
>> > that? How do I call a function exactly at same time from two
>> > different processes?
>>
>> It depends on how you define "called simultaneously".
>>
>> What do you mean "called simultaneously"?
>> What do you want to achieve?
>>
>>         Georgy
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questi...@REDACTED://www.erlang.org/mailman/listinfo/erlang-questions
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>



More information about the erlang-questions mailing list