Hi, I am writing a simple program modeling client/server interaction. I want the server to be capable of handling multiple connections. To implement this, I have been using _beginthreadex, passing references to sockets to the child thread.
For example:
while(1) {
SOCKET sClient = accept(ListenSocket, NULL, NULL);
...
child = (HANDLE) _beginthreadex( NULL, 0, &readFromClient, (void *) &sClient, 0, NULL ));
...
}
Now, if the above code is contained in a while()
loop, occasionally I get errors. Multiple threads have references to the same socket. I assume this is because the line SOCKET sClient = accept(ListenSocket, NULL, NULL);
is run before the value held in sClient
is read by the readFromClient
function. Thus, two (or more) threads could possibly be trying to communicate over the same socket.
What is the best way to ensure that the readFromClient
function executes at least the first line (where the value of the parameter is read) before the value of sClient
is changed? Thanks in advance for your help!