Re: Pass Socket to new thread

2018-08-28 Thread Ivo via Digitalmars-d-learn

Thanks for all your answers.

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




Re: Pass Socket to new thread

2018-08-28 Thread bauss via Digitalmars-d-learn

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( , 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".


Re: Pass Socket to new thread

2018-08-28 Thread Kagamin via Digitalmars-d-learn

while(true) {
auto client = socket.accept();
spawn(, cast(shared)client);
}

void handleConnection(shared Socket sclient) {
Socket client=cast()sclient;
//do stuff like receive and send
}


Pass Socket to new thread

2018-08-28 Thread Ivo via Digitalmars-d-learn
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( , 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.