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:
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:
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
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; }
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; }
I would appreciate any suggestion on improving this and your oppinions.
Thank you
Comment