0

我正在编写一个 C++/Qt 多线程服务器。由于它只是更大应用程序的一部分,因此我必须将收到的所有数据写入队列。比某人的另一部分处理此信息并给出响应,还将其放入队列中。
我想知道是否可以将此响应放在某个线程中的某个套接字,因为到目前为止我想出的唯一想法是发送一个信号,表明响应到达,它会唤醒所有线程并检查它是否是给他们的消息(通过检查套接字描述符)。

我的代码:
thread.h

#pragma once
#include "socket.hpp"
#include <QThread>

class Thread : public QThread
{
    Q_OBJECT
public:
    Thread(int socketId, QObject *parent = 0);
    void run();
signals:
    void error(QTcpSocket::SocketError socketerror);
private:
    int socketDescriptor;
};

线程.cpp

#include "thread.h"
#include <iostream>

Thread::Thread(int socketId, QObject *parent) :
    QThread(parent), socketDescriptor(socketId)
{
}

void Thread::run()
{
    Socket *tcpSocket = new Socket(socketDescriptor, this);
    connect(tcpSocket, SIGNAL(connectionClosed()), SLOT(quit()));
    exec();
}

套接字.h

#pragma once

#include <QTcpSocket>
#include <boost/shared_ptr.hpp>

class Message;

class Socket : public QObject
{
    Q_OBJECT
public:
    Socket(int socketDescriptor, QObject* = 0);
    ~Socket();

    bool isActive();
    void emmiter();
signals:
    void connectionClosed();
private slots:
    void readClient();
    void discardClient();
public slots:
    void sendResponse(boost::shared_ptr<Message>);
private:
    void disconnect();
    quint16 nextBlockSize;
    QTcpSocket* socket;
};

套接字.cpp

void ClientSocket::sendResponse(boost::shared_ptr<Message> msg)
{
    if(this->socket->socketDescriptor() == msg->conn.socket)
    {
            //actuall sending is not important
    }
}

上面的这个^是我知道的,但我知道这不好,特别是如果我有很多线程并且它们都检查socketDescriptor()。此外,我必须从我的Message类中创建一个元对象,以便它可以在信号槽机制中使用。我想只向一个套接字发送信号。我该怎么做 ?将套接字对象放入线程中,并通过将 id 提供给线程来调用方法?有任何想法吗 ?

4

1 回答 1

2

我想知道是否可以将此响应放在某个线程中的某个套接字,因为到目前为止我想出的唯一想法是发送一个信号,表明响应到达,它会唤醒所有线程并检查它是否是给他们的消息(通过检查套接字描述符)。

No, that's not how you do it. A thread is like an employee. When you go to Burger King, you don't ask for Jane. If you see Jeff at the counter, you don't walk past him and go rummaging in the back for Jane to take your order. If she's busy with a customer, but Jeff is available, you don't wait for Jane. You let the first cashier who is available take your order.

When you receive data on a socket, have a thread, any thread, process that information. It doesn't matter which. You don't need to force some one particular thread to do it.

Think about threads as little as possible. They're just the vehicles that do the work. You should focus on what work you want done and the code to do it. If you have to think about the mechanics of assigning the work to workers excessively, you are doing something wrong.

If you have have cashiers (who can't cook) and cooks (who can't take orders), you'll always have to look around for the right employee to get the job done. But all threads are fundamentally equal, and equally capable of doing any job, so you only have this nightmare if you force yourself into it.

于 2013-01-12T14:01:04.663 回答