Pass Socket to new thread
bauss
jj_1337 at live.dk
Tue Aug 28 11:56:21 UTC 2018
On Tuesday, 28 August 2018 at 10:48:20 UTC, Ivo wrote:
> I'm writing a basic server program and I want to handle each
> connection received in a new thread.
>
> So here is the code I'm trying to produce:
>
> while(true) {
> auto client = socket.accept();
> spawn(&handleConnection , client);
> }
>
> void handleConnection(Socket client) {
> //do stuff like receive and send
> }
>
> I get the error that I cannot pass "client" to "spawn" since it
> is not a "shared" or "immutable" object.
> So I need to create an "immutable" (or "shared") copy of the
> socket in order to pass it to the "handleConnection" function.
> However doing so would prevent me from sending/receiving data.
> That is "client.receive" and "client.send" do not work if
> "client" is "shared" or "immutable".
>
> Any suggestions to solve my problem? Thanks.
What you should do instead is using a non-blocking socket in a
single thread and only if necessary use a thread-pool design to
split multiple sockets into multiple threads, but each thread
should still be shared by multiple sockets. Using fibers can help
you do that without reinventing the wheel.
Usually it's __never__ a good idea to spawn a thread per
connection. In fact it'll only come with synchronization issues
in the end and then you end up putting mutexes everywhere, which
is just going to put your performance downhill.
Especially with sockets and threading you want the design to be
correct from the beginning, because once your application starts
to depend on your design, then it's going to be hard to
re-implement or replace the current system to do it the "right
way".
More information about the Digitalmars-d-learn
mailing list