# Erlang "ping pong" concurrent programming example translated into SWI Prolog

**URL:** <https://swi-prolog.discourse.group/t/erlang-ping-pong-concurrent-programming-example-translated-into-swi-prolog/1510>\
**Category:** Nice to know\
**Tags:** erlang\
**Created:** [November 15, 2019, 2:13pm UTC](https://swi-prolog.discourse.group/t/erlang-ping-pong-concurrent-programming-example-translated-into-swi-prolog/1510 "2019-11-15T14:13:33Z")\
**Posts on this page:** 1\
**Showing post:** 11

<div class="post-metadata">

**Author:** ![joeblog](https://yyz2.discourse-cdn.com/free1/user_avatar/swi-prolog.discourse.group/joeblog/32/122_2.png) [@joeblog](https://swi-prolog.discourse.group/u/joeblog)\
**Post date:** [November 16, 2019, 5:46pm UTC](https://swi-prolog.discourse.group/t/erlang-ping-pong-concurrent-programming-example-translated-into-swi-prolog/1510/11 "2019-11-16T17:46:15Z")

</div>

Using repeat/0 with fail/0 is purely optional, and pong could be written without it like so:

```prolog
ping(0, Pong_PID) :-
    thread_send_message(Pong_PID, 'finished'),
    format("Ping finished~n", []), !.

ping(N, Pong_PID) :-
    thread_self(Ping_PID),
    thread_send_message(Pong_PID, msg('Ping', Ping_PID)),
    thread_get_message(Ping_PID, Msg),
    format("Ping received ~w~n", [Msg]),
    succ(M, N),
    ping(M, Pong_PID).

pong :-
    thread_get_message(Msg),
    ( Msg \== 'finished'
    -> msg(Ping, Ping_PID) = Msg,
         format("Pong received ~w~n", [Ping]),
         thread_send_message(Ping_PID, 'Pong'),
         pong
    ; format("Pong finished~n", [])
    ). 

start :-
    thread_create(pong, Pong_PID),
    thread_create(ping(3, Pong_PID), Ping_PID),
    thread_join(Pong_PID),
    thread_join(Ping_PID).

```

I explained why I prefer to write listening loops as failure driven loops rather than recursively previously at [Some notes on writing a concurrent programing Howto. Comments and corrections welcome](https://swi-prolog.discourse.group/t/some-notes-on-writing-a-concurrent-programing-howto-comments-and-corrections-welcome/1431)

---

_[View the full topic](https://swi-prolog.discourse.group/t/erlang-ping-pong-concurrent-programming-example-translated-into-swi-prolog/1510)._
