Qt moveToThread() vs calling new thread when do we use each

前端 未结 2 444
傲寒
傲寒 2020-12-31 23:22

When do we use each of this function calls in a threaded application. given two functions fun1() and fun2() defined in the same class dealing with read/write of data into bu

2条回答
  •  遥遥无期
    2020-12-31 23:48

    Like Piotr answered you should really have a look at the link he suggested.
    As I understand your problem, that should solve your problem.
    This is the simplified code from that blog:

    class Producer  
    {  
    public:
        Producer();  
    
    public slots:
        void produce()
        { //do whatever to retrieve the data
          //and then emit a produced signal with the data
          emit produced(data);
          //if no more data, emit a finished signal
          emit finished();
        }
    
    signals:
        void produced(QByteArray *data);
        void finished();
    };
    
    class Consumer
    {
    public:
        Consumer();
    
    public slots:
        void consume(QByteArray *data)
        {
           //process that data
           //when finished processing emit a consumed signal
           emit consumed();
           //if no data left in queue emit finished
           emit finished();
        }
    };
    
    int main(...)
    {
        QCoreApplication app(...);
    
        Producer producer;
        Consumer consumer;
    
        producer.connect(&consumer, SIGNAL(consumed()), SLOT(produce()));
        consumer.connect(&producer, SIGNAL(produced(QByteArray *)), SLOT(consume(QByteArray *));
    
        QThread producerThread;
        QThread consumerThread;
        producer.moveToThread(&producerThread);
        consumer.moveToThread(&consumerThread);
    
        //when producer thread is started, start to produce
        producer.connect(&producerThread, SIGNAL(started()), SLOT(produce()));
    
        //when consumer and producer are finished, stop the threads
        consumerThread.connect(&consumer, SIGNAL(finished()), SLOT(quit()));
        producerThread.connect(&producer, SIGNAL(finished()), SLOT(quit()));
    
        producerThread.start();
        consumerThread.start();
    
        return app.exec();
    }
    

提交回复
热议问题