[Interest] Never ending thread: blocking GUI

Lincoln Ramsay a1291762 at gmail.com
Wed Oct 17 01:15:28 CEST 2012


On 17/10/12 01:00, Sensei wrote:
> So, if in my main thread every time I need to search I will create a
> thread, a searcher, move the searcher to the new thread.

You should probably just keep these objects around rather than 
recreating them all the time.

> Am I leaking memory?

Yes...

> How can I delete these objects?

Unfortunately, it's a little more complicated to clean up threads. 
Here's a suggestion.


class MyObject : public QObject
{
   Q_OBJECT
private:
     QThread *thread;
     Searcher *searcher;

public:
     MyObject(QObject *parent = 0)
     : QObject(parent)
     {
     startThread();
     }

     ~MyObject
     {
     stopThread();
     }

     void startThread()
     {
     thread = new QThread;
     thread->start();
     searcher = new Searcher;
     searcher->moveToThread(thread);
     connect(this, SIGNAL(search(QStringList)), searcher, 
SLOT(search(QStringList)));
     connect(searcher, SIGNAL(searchResults(QString)), this, 
SLOT(searchResults(QString)));
     }

     void stopThread()
     {
     searcher->deleteLater(); // schedule a delete of the object
     thread->quit(); // schedule the thread for termination
     thread->wait(); // this will block until the above two operations 
have completed
     delete thread;
     }

     void doSearch()
     {
     QStringList terms;
     terms << "*.txt";
     emit search(terms);
     }

signals:
     void search(const QStringList &terms);

public slots:
     void searchResults(const QString &file)
     {
     qDebug() << "got search result" << file;
     }
};

-- 
Link




More information about the Interest mailing list