How Can I use db in threads? Requested database does not belong to the calling thread.



  • How to use database in threads? I create instance of db in main thread and give threads pointers. But it crashes, also I tried to create instance in Thread, it doesn't work. How Can I use db in threads?

    #ifndef THREAD_H
    #define THREAD_H
    
    #include <QThread>
    #include <QTcpSocket>
    #include <QRegularExpression>
    
    #include "dbmanager.h"
    
    class MyThread : public QThread
    {
      Q_OBJECT
    
      public:
        explicit MyThread(qintptr ID, QObject *parent = nullptr);
        ~MyThread();
    
        void run();
    
      signals:
        void error(QTcpSocket::SocketError socketerror);
    
      public slots:
        void readyRead();
        void disconnected();
    
      private:
        QTcpSocket *socket;
        qintptr socketDescriptor;
    
        DB_Manager * db;
    
        void analysis(QString httpRequest, QString& method, QString& uri, QString& body);
    };
    
    #endif // THREAD_H
    
    void MyThread::run()
    {
      socket = new QTcpSocket();
    
      if (!socket->setSocketDescriptor(this->socketDescriptor) )
      {
        emit error (socket->error());
        return;
      }
    
      connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()),Qt::DirectConnection );
      connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    
      exec();
    }
    
    void HttpServer::incomingConnection(qintptr socketDescriptor)
    {
        MyThread *thread = new MyThread(socketDescriptor, this);
        connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    
        thread->start();
    }
    

    In MyThread function:

    QJsonDocument dbody = QJsonDocument::fromJson(body.toLocal8Bit());
                QString password = dbody.object()["password"].toString();
    
                int id = db->getIdByLog(tname.toStdString(), password.toStdString());
    
                if(id != 0)
                {
                    sendLog(true, id);
                }
                else
                {
                    sendLog(false, 0);
                }
    

  • Lifetime Qt Champion

    Hi,

    What is DB_Manager ?
    Where do you allocate it ?
    How is it implemented ?


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.