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!

Recommended Answers

All 3 Replies

Interesting...
Haven't thought about this much, but I guess a relatively straight forward method is to store the sClient on the heap, hand a pointer to it over to the thread.. and then copy it to the thread's local storage, finally free the memory you allocated on the heap in the thread.

Another scenario would involve locks, where this snippet would attempt to acquire a lock before changing sClient... you'd also have to hand over this lock to the thread, that will unlock it when it is done reading the sClient.

I implemented this using the malloc/free method mentioned above. I simply malloc before the call to _beginthreadex() , then free as soon as I copy the value from within the function. As I am relatively new to c++, I wonder if there is any risk of the memory not being freed? Can the thread creation fail, causing a memory leak from the allocated space for the SOCKET? This seems to be a very unlikely scenario, but I'd like to learn as much as I can about defensive programming in c++.

Thanks to thelamb!

Hmm, malloc/free are C functions, if you can avoid it you shouldn't really use them in C++. Look at new/delete instead.

You have the right mindset to become a good C/C++ coder. It is always a must to check the return value of functions. _beginthreadex can definitely fail and when it does, you must delete the memory you just created.

Even if you didn't have this dynamic memory you'd still want to check the return value of beginthreadex though, to break out of this while loop and inform the user that something went wrong.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.