0

My threadcheck.h

        #include <QThread>
        #include <QDebug>
        #include <QMutex>
        class ThreadCheck : public QThread
        {
            Q_OBJECT
        public:
            explicit ThreadCheck(QObject *parent = 0);
            int Val() const;

        signals:
            void signalReceived();

        protected:
            void run();
        public slots:
            void slotReceived();
        private:
            QMutex mutex;
            int num;

        };

My threadcheck.cpp file is

         #include "threadcheck.h"
        ThreadCheck::ThreadCheck(QObject *parent) :
            QThread(parent)
        {
            connect(this,SIGNAL(signalReceived()),this,SLOT(slotReceived()));
            num = 0;
        }

        int ThreadCheck::Val() const
        {
            return num;
        }


        void ThreadCheck::slotReceived()
        {
            mutex.lock();
            qDebug() << "hello";
            mutex.unlock();
        }


        void ThreadCheck::run()
        {
            while(1)
            {
                emit signalReceived();
            }

        }   

main .cpp is

        #include <QCoreApplication>
        #include "threadcheck.h"
        int main(int argc, char *argv[])
        {
            QCoreApplication a(argc, argv);
            ThreadCheck threadCheck;
            threadCheck.start();
            while(1);
            return a.exec();
        }   

When i start this thread from main , it does not show any output slot never execute. Ideally it should keep printing hello.

Please suggest a solution.

sanjay
  • 735
  • 1
  • 5
  • 23
  • 1
    There isn't enough information in you post to answer it. Do you get any errors, is the signals connected to the slot? – Matti Lyra Nov 13 '12 at 08:42
  • no there are no error.But it does not how hello at all. – sanjay Nov 13 '12 at 08:49
  • edit this post and add the exact line used to connect the signal to the slot, and check the return value of connect. Make sure it is not `false` – UmNyobe Nov 13 '12 at 08:59
  • connect() returns true when i connected them in main – sanjay Nov 13 '12 at 09:08
  • using a mutex is useless if you are only locking and unlocking in `run()` and slots which are only called with signals, because they will never execute concurrently. – UmNyobe Nov 13 '12 at 09:31
  • Actually i will do a lot of other stuff in run.I will get data from serial port.So i need to lock mutex. This is only an example to reproduce the problem – sanjay Nov 13 '12 at 12:25

2 Answers2

3

Remove the while(1) in your main function.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
1

Without much noise being made about it, sub-classing QThreads and overwriting the run() method is not the way to work with threads in Qt any more.

Please read this blog. It saved me hours of headaches. It is not clear when did this change take place, but the example code in that post is now in the official documentation of Qt 5.x