Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is closesocket thread safe?

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?

like image 604
shawn Avatar asked Mar 25 '12 15:03

shawn


2 Answers

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.

like image 78
R.. GitHub STOP HELPING ICE Avatar answered Nov 12 '22 09:11

R.. GitHub STOP HELPING ICE


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.

like image 33
Martin James Avatar answered Nov 12 '22 09:11

Martin James