Vedant
Vedant

Reputation: 155

Do we need to lock class member functions if its objects are running in multiple threads

I am working with C++ based Networking project using winsock library. The code is:

class NetworkCom
{
private:
    SOCKADDR_IN ClientAddress;
    int ClientAddressSize;
    SOCKET SenderSocket;
public:
    NetworkCom(SOCKET& sock)
    {
        ClientAddressSize = sizeof(ClientAddress);
        getpeername(sock,(SOCKADDR*)&ClientAddress,&ClientAddressSize);

        sock = socket(AF_INET,SOCK_STREAM,0);
        SenderSocket = socket(AF_INET,SOCK_STREAM,0);
    }

    int SendData(char message[])
    {
        int val;
        val = send(sock,message,sizeof(message),0); // if val <= 0 then error
        return val;     
    }   

    string RecieveData()
    {
        string message;
        char msg[100];

        connect(SenderSocket,(SOCKADDR*)&ClientAddress,&ClientAddressSize);
        recv(SenderSocket,msg,100,0);
        message = msg;

        return message;
    }

    ~NetworkCom()
    {
        cout<<"Closing Connection..";
        closesocket(SenderSocket);
        closesocket(sock);
    }
  };

I am going to create a new NetworkCom Object for each new client in a new thread. So when i do so do i need to use mutex to lock the member function of the class evertime a object in a thread is using the member function SendData and RecieveData.

If i have to use mutex.... Is there any way this can be done without mutex

Upvotes: 0

Views: 105

Answers (1)

ComicSansMS
ComicSansMS

Reputation: 54777

As most socket APIs, Winsock does not like concurrent access to the same socket:

send should not be called on the same stream-oriented socket concurrently from different threads, because some Winsock providers may split a large send request into multiple transmissions, and this may lead to unintended data interleaving from multiple concurrent send requests on the same stream-oriented socket.

From MSDN, recv has similar constraints.

So if you are sharing the same socket between multiple threads, all access to that socket need to be synchronized. A mutex is one way of achieving this synchronisation. If you are using different sockets for the different threads though, you do not need to synchronize, as long as you are not sharing any other (mutable) data between threads.

Upvotes: 2

Related Questions