简体   繁体   中英

Can I call socket send() from different threads?

If I have a socket called s , can I do this in different threads:

Thread 1:

send(s, "Hello from Thread 1");

Thread 2:

send(s, "Hello from Thread 2");

Is it guaranteed that these two strings will be placed in the send buffer one after the other (I don't care which one is placed first), or is there a possibility that they could get mixed together?

Note: maybe this question should have been titled: "Is socket send() thread safe" (but I am not really sure what thread safety means).

The answer is no. Generally send() does not guarantee that the data is being sent in one piece. You always need to check the value returned by send() in order to find out how many bytes actually have been sent. If this is less than the size of your buffer (which is not an error), you have to call send() again, appropriatly in a loop, eg something like this:

char *msg="Hello from thread 1";
size_t pos;
size_t currentBytes;
size_t BytesToSend=strlen(msg);

for (pos=0 ; pos < BytesToSend ; pos += currentBytes) {
    currentBytes = send(s, msg + pos, BytesToSend - pos, 0);

    if (currentBytes <= 0) {
       // error occurred (-1) or connection has been closed on remote site (0)
       return ...
    }
}

That means that you data may arrive in pieces, and when sending from two threads the data may be mixed together.

See also send() reference, especially

If no error occurs, send returns the total number of bytes sent, which can be less than the number requested to be sent in the len parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM