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:
Expand|Select|Wrap|Line Numbers
- 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:
Expand|Select|Wrap|Line Numbers
- 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