Do I need to add blocking to Recv / Send / Close code for the same socket among streams

From posts like this , I know that on linux the recv / send functions are thread safe and the user is allowed to work on the same socket from different threads at the same time.

Although this is not a very good design, in the following situation I am wondering what we should do with the user-level code to preserve data integrity and health state: There are threads in the same sockets, the first for creating and closing a socket, the second for reading the socket and the last to send sockets. See Pseudo Code

 struct SocketInfo
 {
      int SockFd;
      int SockType;
      queue<Packet*> RecvPacks;
 };

 map<int, SocketInfo*> gSocketInfoMap;
 pthread_mutex_t       gSocketsLock;

 //Thread1
 pthread_mutex_lock(&gSocketsLock);
 // get information for sock
 SocketInfo* info = gSocketInfoMap[sock];
 pthread_mutex_unlock(&gSocketsLock);

 close(sock);         // line-1
 .....


 //thread-2
 pthread_mutex_lock(&gSocketsLock);
 SocketInfo* info = gSocketInfoMap[sock];
 pthread_mutex_unlock(&gSocketsLock);

 recv(sock, buffer, sizeof(buffer));         // line-2
 .....

 //thread-3
 pthread_mutex_lock(&gSocketsLock);
 SocketInfo* info = gSocketInfoMap[sock];
 pthread_mutex_unlock(&gSocketsLock);

 send(sock, buffer, sizeof buffer);         // line-3
 .....

      

I wonder if I need to move Line-1, Line-2 and Line-3 to the gSocketsLock protection area? Why?

+3


source to share


1 answer


As stated in the related question, socket operations are thread safe. In any case, receiving and sending data are independent operations that do not interfere with each other.

Obviously, you shouldn't close a socket that is actively being read and written, but placing close()

inside a critical section does nothing to prevent this error. Whatever mechanism ensures that active sockets are not closed or that closed sockets are not available is at a higher level than the critical sections shown in the OP.



If one thread closes a socket that another thread is trying to use for I / O, the worst thing that can happen is that the recv / send call will return an error.

In short: no, it would be nice to put socket operations inside the critical section. It was not helpful and it unnecessarily increases the likelihood of blocking.

+3


source







All Articles