Given a server that receives connections from clients, does some work, then after the nth connection is shutdown, it either shuts down itself or starts ignoring connections by doing nothing when the clients connect. I want the thread that established the server to wait for the server to communicate that information (that it has closed its nth connection) to continue its execution.
Expected behaviour:
let t = Thread.create (Unix.establish_server loop) addr in
f1 ();
wait_for_loop_signal ();
f2 ();
I tried doing that with Thread.join
in that case I would need to kill/stop the thread t
to continue:
let t = Thread.create (Unix.establish_server loop) addr in
f1 ();
Thread.join ();
f2 ();
But it doesn't work, because loop
is executed on a separate thread after each connection. So the code of loop
is executed on child threads spawned by establish_server
. And the thread on which establish_server
is executed in not accessible from loop
unless there is a way for a thread to kill its parent.
Using Event, by having loop
send a message through a channel provided by the initial thread, with Event.sync (Event.send channel ())
:
let channel = Event.new_channel () in
let t = Thread.create (Unix.establish_server (loop channel)) addr in
f1 ();
let _ = Event.sync (Event.receive channel) in
f2 ();
But in this case, the execution blocks at let _ = Event.sync (Event.receive channel) in
. The send
is called correctly and get executed inside loop. But the message that was sent through the channel never gets read by receive
. I am not sure why.
CodePudding user response:
The function Unix.establish_server
launches a new process and not a thread for each connection. Since the server forks new processes with separate memory, the only way to communicate is trough an inter-process communication mechanism, for instance another socket. Neither Thread.join
nor Events
can be used meaningfully with establish_server
. Similarly, there is no shared memory between the various connections.
In other words, if you want more control on the server, the function establish_server
is not the one that you are looking for.