fuCtor / QAMQP

AMQP implementation for Qt
Other
28 stars 3 forks source link

How to use QAMQP not from main thread? #8

Open OlegJakushkin opened 11 years ago

OlegJakushkin commented 11 years ago

So I tried to modify test sample presented with lib to something like:

#include <QObject>
#include "qamqp/amqp.h"
#include "qamqp/amqp_exchange.h"
#include "qamqp/amqp_queue.h"
#include <QPointer>
#include <QThread>

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/date_time.hpp>
class OutThread : public QThread
{
    Q_OBJECT
protected:
    QPointer<QAMQP::Client> client_out;
    QPointer<QAMQP::Exchange> exchange_out;

    void run()
    {
        std::cout << "w1" << std::endl;

        QUrl con(QString("amqp://guest:guest@localhost:5672/"));
        client_out = new QAMQP::Client(this);
        client_out->open(con);
        exchange_out =  client_out->createExchange("test.test2");
        exchange_out->declare("fanout");

        QAMQP::Exchange::MessageProperties properties;
        properties[QAMQP::Frame::Content::cpDeliveryMode] = 2; // Make message persistent
        std::cout << "w2" << std::endl;

        while(1){
            exchange_out->publish("123 123 123", exchange_out->name(), properties);
            boost::this_thread::sleep(boost::posix_time::milliseconds(1));
        }
        std::cout << "w3" << std::endl;

        exec();
    }
};

class Test : public QObject
{
    Q_OBJECT

public:
    Test(){}
    ~Test(){}

    Q_INVOKABLE void test() {
        std::cout << "t1" << std::endl;

        OutThread oThread;
        oThread.start();
        //InThread iThread;
        //iThread.start();
        std::cout << "t2" << std::endl;

        oThread.wait(); 
        std::cout << "t3" << std::endl;

    };
};

yet it cannot create a connection from another thread and talls me:

t1
t2
w1
QObject::setParent: Cannot set parent, new parent is in a different thread
w2

How to fix QAMQP in order to support new threads?

fuCtor commented 11 years ago

Because OutThread is in main thread but Test is in OutThread.

May be this link will be usefull: http://codethis.wordpress.com/2011/04/04/using-qthread-without-subclassing/ http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ http://habrahabr.ru/post/150274/