Qt,关于UDPlink的线程安全
Qt, thread safety regarding UDPlink
如果我有一个Qt的UDPlink和一个像这样的writeBytes函数:
void UDPLink::writeBytes(const char* data, qint64 size)
{
// Broadcast to all connected systems
for (int h = 0; h < hosts.size(); h++)
{
QHostAddress currentHost = hosts.at(h);
quint16 currentPort = ports.at(h);
socket->writeDatagram(data, size, currentHost, currentPort);
}
}
这里的套接字是一个 UDP 套接字。此函数线程安全吗?也就是说我可以从 2 个不同的线程调用 writeBytes() 函数吗?
唯一可能不是螺纹安全的 2 个部分:
一个是数据报可能会交错(无论如何都会在UDP中发生,所以不用担心)
另一件事是QUdpSocket::writeDatagram
不是线程安全的。因此,您要么需要将套接字的访问与互斥锁同步,要么使用信号/插槽,或者为每个线程创建一个套接字。
使其线程安全很容易:
//make it a slot or invokable
void UDPLink::writeBytes(const char* data, qint64 size)
{
if(QThread::currentThread() != thread())
{
QByteArray buff(data, size);//makes a copy pass in a QByteArray to avoid
QMetaObject::invokeMethod(this, "writeBytes", Q_ARG(QByteArray, buff));
//this forward the call to the thread that this object resides in if the calling thread is different.
return;
}
for (int h = 0; h < hosts.size(); h++)
{
QHostAddress currentHost = hosts.at(h);
quint16 currentPort = ports.at(h);
socket->writeDatagram(data, size, currentHost, currentPort);
}
}
答案是否定的,QUDPsocket不是线程安全的,而是可重入的,这意味着您不能使用相同的实例从2个不同的线程调用QUDPSocket->writeDatagram/writeBytes,但您可以从QUDPSocket的单独实例调用调用QUDPSocket->writeDatagram/writeBytes
相关文章:
- 如何将元素添加到数组的线程安全函数?
- C++中的线程安全删除
- 在std::thread中,joinable()然后join()线程安全吗
- 在c++队列中使用pop和visit实现线程安全
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 全局变量 多读取器 一个写入器多线程安全?
- 共享队列的线程安全
- boost::文件系统::recursive_directory_iterator多线程安全
- 以线程安全的方式转换 C/C++ 中时区名称字符串的时区偏移量
- 线程安全运算符<<
- 如何使缓存线程安全
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 提升精神 V2 Qi 语法线程安全吗?
- asio 链对象线程安全吗?
- 线程安全队列 c++
- 提供对不同类型的数据(建议、代码审查)的线程安全访问的类
- 如何以线程安全的方式更改目录?
- 线程安全的引用计数队列C++
- 析构函数和线程安全
- 适用于大型数组的无复制线程安全环形缓冲区