Is it safe if I want to call closesocket() on a server socket from 1 thread which is separate from another thread which runs the server using the same server socket?
The call itself is thread-safe, but the practice is not. Whenever you're deallocating a resource whose identifier could be reused after it's deallocated, you must synchronize with all threads that could possibly use it. Otherwise, it's possible that, after the resource is deallocated, a new resource (in your case, socket) could be allocated with the same identifier (socket number), and code intending to access the (now closed) server socket could end up operating on a different socket.
The degree to which this is dangerous (and whether it can happen at all) depends a lot on your code. It might not happen if you never create any more sockets after closing the server socket. But it's still conceptually very wrong, and anyone competent reviewing your code would consider this very bad.
Edit: The solution to problems like this is protection of the resource descriptor (not the resource itself) with a reader-writer lock (rwlock). Accessing the resource descriptor (the integer variable holding the socket number, in your case) requires holding a "read" lock on it, whether you'll be performing input or output or other operating using the resource it refers to. Deallocating the resource (and storing a sentinel value like -1 in the variable holding the descriptor) requires a write lock.
Yes, it's not a problem. Naturally, there will be exceptions/errors generated in the other thread/s that have calls outstanding on the socket, but the network stack itself, (which has to be thread-safe because of all the different processes/threads that are normally using it), will not be damaged.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With