Thread overview
Pass Socket to new thread
Aug 28, 2018
Ivo
Aug 28, 2018
Kagamin
Aug 28, 2018
bauss
Aug 28, 2018
Ivo
August 28, 2018
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.
August 28, 2018
while(true) {
    auto client = socket.accept();
    spawn(&handleConnection, cast(shared)client);
}

void handleConnection(shared Socket sclient) {
    Socket client=cast()sclient;
    //do stuff like receive and send
}
August 28, 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".
August 28, 2018
Thanks for all your answers.

I'll have a look at the design and use casting if necessary.