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

标签 c++ qt

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

相关文章:

c++ - 如何确定作业的两个副作用是否未排序?

C++11 快速 constexpr 整数幂

c++ - 强制 QPlainTextEdit 大写字符

c++ - 将 openCV .dll 文件添加到 Netbeans C++ Qt 应用程序

c++ - c++中 map 的反向迭代丢失了第一个元素

c++ - ADL 在 constexpr 函数中不起作用(仅限 clang)

c++ - 如何获得鼠标点击的位置(以 x-y 坐标像素为单位)?

c++ - MacOS 上的 Qt .nib 问题

Python/PyQt4 : How to make a QComboBox Item draggable

c++ - 从类的 QList 访问 protected 成员,例如 QList<Account*>