To teach myself Erlang, I’ve started working through its “getting started” documentation (which is excellent). I generally find the best way to learn a new programming language is to translate examples into a language I’m more comfortable with, so that’s what I’ve done here with the “ping pong” example at https://erlang.org/doc/getting_started/conc_prog.html#message-passing
My translation into SWI Prolog bellow works, but I’m sure more experienced programmers will have tips on how to improve it.
ping(0, _PingQueue, PongQueue) :-
thread_send_message(PongQueue, 'finished'),
format("Ping finished~n", []), !.
ping(N, PingQueue, PongQueue) :-
thread_send_message(PongQueue, msg('Ping', PingQueue)),
thread_get_message(PingQueue, Msg),
format("Ping received ~w~n", [Msg]),
succ(M, N),
ping(M, PingQueue, PongQueue).
pong(PongQueue) :-
repeat,
thread_get_message(PongQueue, Msg),
( Msg \== 'finished'
-> msg(Ping, PingQueue) = Msg,
format("Pong received ~w~n", [Ping]),
thread_send_message(PingQueue, 'Pong'),
fail
; format("Pong finished~n", []),
!
).
start :-
setup_call_cleanup( (message_queue_create(PingQueue),
message_queue_create(PongQueue)
),
(thread_create(ping(3, PingQueue, PongQueue), PingThread),
thread_create(pong(PongQueue), PongThread)
),
(thread_join(PingThread),
thread_join(PongThread),
message_queue_destroy(PingQueue),
message_queue_destroy(PongQueue)
)
).