gpt4 book ai didi

c++ - Qt,关于UDPlink的线程安全

转载 作者:太空狗 更新时间:2023-10-29 21:41:23 25 4
gpt4 key购买 nike

如果我有一个 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);
}
}

关于c++ - Qt,关于UDPlink的线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29012933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com