如果我有一个 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/