简体   繁体   English

从多个线程中的相同UDP套接字发送

[英]Sending from the same UDP socket in multiple threads

I have multiple threads which need to send UDP packets to different IP addresses (only to send, nothing needs to be received). 我有多个线程需要将UDP数据包发送到不同的IP地址(仅发送,不需要接收)。 Can I reuse the same UDP socket in all the threads? 我可以在所有线程中重用相同的UDP套接字吗?

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. 由于数据包是单独发送的,虽然它们的接收顺序是不确定的,但它已经是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. 虽然,如果您正在使用套接字执行其他操作,例如bind(),close(),那么您最终可能会遇到竞争条件,因此您可能需要小心。

System calls are supposed to be atomic, so formally it seems fine for UDP. 系统调用应该是原子的,所以对于UDP来说似乎很正常。 Then kernels have bugs too and you are inviting all sorts of nasty surprises. 然后内核也有bug,你正在邀请各种令人讨厌的惊喜。 Why can't you use socket per thread? 为什么不能为每个线程使用套接字? It's not like with TCP where you need a connection. 它与TCP不同,您需要连接。 As an added bonus you'd get a separate send buffer for each descriptor. 作为额外的奖励,您将为每个描述符获得单独的发送缓冲区。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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