开发者

Sending from the same UDP socket in multiple threads

开发者 https://www.devze.com 2023-01-11 17:23 出处:网络
I have multiple threads which need to send UDP packet开发者_如何学运维s to different IP addresses (only to send, nothing needs to be received). Can I reuse the same UDP socket in all the threads?Yes,

I have multiple threads which need to send UDP packet开发者_如何学运维s to different IP addresses (only to send, nothing needs to be received). Can I reuse the same UDP socket in all the threads?


Yes, I think you can.

As the packets are sent out individually, although the order they are received will be nondeterministic, it is already with UDP.

So sending in multiple threads in the same socket is fine.

Although, if you're doing other stuff with the socket, such as bind(), close(), then you could end up with race conditions, so you might want to be careful.


System calls are supposed to be atomic, so formally it seems fine for UDP. Then kernels have bugs too and you are inviting all sorts of nasty surprises. Why can't you use socket per thread? It's not like with TCP where you need a connection. As an added bonus you'd get a separate send buffer for each descriptor.

0

精彩评论

暂无评论...
验证码 换一张
取 消