If I have a Qt's UDPlink and a writeBytes function like this:
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);
}
}
Here the socket is a UDP socket. Is this function thread safe? That is can I call the writeBytes() function from 2 different threads?
The only 2 parts that may be not thread safe:
one is that is that datagrams may get interleaved (which happens anyway with UDP so no worries)
The other thing is that QUdpSocket::writeDatagram
is not thread safe. So you either need to synchronize access to socket with a mutex or using the signal/slots or make a socket for each thread.
making it thread safe can be easy:
//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调用
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.