Are parallel calls to send/recv on the same socket valid?

前端 未结 3 2037
花落未央
花落未央 2020-11-22 17:24
  1. Can we call send from one thread and recv from another on the same socket?
  2. Can we call multiple sends parallely from different threads on the same socket?
3条回答
  •  轮回少年
    2020-11-22 17:40

    I don't see how receiving in parallel could possibly accomplish anything. If you have a 3 bytes message, 1 thread could get the 1st 2 bytes and another the last byte, but you'd have no way of telling which was which. Unless your messages are only a byte long, there is no way you could reliably make anything work with multiple threads receiving.

    Multiple sends might work, if you sent the entire message in a single call, but I'm not sure. It's possible that one could overwrite another. There certainly wouldn't be any performance benefit to doing so.

    If multiple threads need to send, you should implement a synchronized message queue. Have one thread that does the actual sending that reads messages from the queue and have the other threads enqueue whole messages. The same thing would work for receiving, but the receive thread would have to know the format of the messages so it could deserialize them properly.

提交回复
热议问题