Linux套接字使用多个线程发送 [英] Linux socket using multiple threads to send

查看:62
本文介绍了Linux套接字使用多个线程发送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非阻塞套接字,它向多个目标发送udp数据包,并在同一套接字上接收所有这些对象的响应.我正在读一个专用线程,但是写(sendto)可能来自几个不同的线程.

I have a single non-blocking socket sending udp packets to multiple targets and receiving responses from all of them on the same socket. I'm reading in a dedicated thread but writes (sendto) can come from several different threads.

在没有任何其他同步的情况下这是安全的吗?持有互斥体时需要写东西吗?或者,写操作是否需要来自同一线程,并且我需要一个队列?

Is this a safe without any additional synchronization? Do I need to write while holding a mutex? Or, do writes need to come from the same thread and I need a queue?

推荐答案

内核将为您同步对底层文件描述符的访问,因此您不需要单独的互斥体.如果您使用的是TCP,则这种方法会出现问题,但是由于我们在谈论UDP,因此这应该是安全的,尽管不一定是最好的方法.

The kernel will synchronize access to underlying file descriptor for you, so you don't need a separate mutex. There would be a problem with this approach if you were using TCP, but since we are talking about UDP this should be safe, though not necessarily best way.

这篇关于Linux套接字使用多个线程发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆