Do I need to lock socket access when transferring data in multi-threaded application?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • emibt08
    New Member
    • Oct 2008
    • 25

    Do I need to lock socket access when transferring data in multi-threaded application?

    Hi,

    I have an application that I recently revised. It transfers data between 2 programs, including files as well as small data chunks. I never had a problem (got garbage at the other side) or anything like that, but I am curious whether I need to lock the socket access when i am sending. An oversimplified example of a single send would be like:

    Code:
    bool sendData(SOCKET sock, uint32_t size, const char * data)
    {
    	uint32_t nSizeNetOrder = htonl(size);
    	const char * pSize = reinterpret_cast<const char*>(&nSizeNetOrder);
    	send(sock, pSize, sizeof(uint32_t), 0);
    	send(sock, data, size, 0);
    	return true;
    }
    Of course, I have many checks, sending data in parts etc. But the point is that in this scenario, for every send that I make there are at least 2 calls to send. Sometimes more, if there's more data.
    Now if multiple threads are trying to send data on the same socket, my logic dictates that at some point this may get corrupted. Ex, one thread sends the size, then another thread sends the size, then the 1st thread starts sending data etc. As I said, it hasn't happened before, but I would like to make sure, so maybe I should do:

    Code:
    bool sendData(SOCKET sock, uint32_t size, const char * data)
    {
    	lock();
    	uint32_t nSizeNetOrder = htonl(size);
    	const char * pSize = reinterpret_cast<const char*>(&nSizeNetOrder);
    	send(sock, pSize, sizeof(uint32_t), 0);
    	send(sock, data, size, 0);
    	unlock();
    	return true;
    }
    Where lock/unlock would use some OS primitives for the task (like mutex).
    I would appreciate any suggestion on improving this and your oppinions.

    Thank you
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    That is actually a platform specific question we would need to know the OS and platform you are running on.

    However since you use SOCKET I am assuming its Windows in which case the answer I believe is yes (or at least that is how I did it last and I assume I had a good reason to do it that way). Generally you should not assume anything about the multi-tasking capabilities of third party libraries and if the documentation says nothing about it then you should assume that they don't handle it.

    In your second source listing I would move lock() down a couple of lines, only protect the minimum that actually requires protection because the less time you keep the lock the more easily you program will flow.

    Comment

    • emibt08
      New Member
      • Oct 2008
      • 25

      #3
      Thanks for your response Banfa, that clears up the hesitation.

      Comment

      Working...