Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

    Beginner: Thread/sleep/Q

    General and Desktop
    3
    3
    2333
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • G
      ginar last edited by

      Hi all;
      Follow it's my firs program with Thread:
      @int main(int argc, char *argv[])
      {
      QApplication a(argc, argv);
      MainWindow w;
      w.show();
      //--------------------------------
      ComQThread COMContex;
      COMContex.start();

      while(1)
      {
          COMContex.write("AlaMaKota"); //do nothing just only write to threads' Queue
      }
      //--------------------------------
      
      return a.exec();
      

      }@

      Let's have a look at thread:
      @void ComQThread::run(){
      QString stringWrite;

      while(1)
      {
          if(!pQueueWrite->isEmpty())
          {
              stringWrite=pQueueWrite->dequeue();
              qDebug()<<stringWrite;
          }
         msleep(1);
      }
      

      }
      //-----------

      void ComQThread::write(QString string){
      pMutex->lock();
      pQueueWrite->enqueue(string);
      pMutex->unlock();
      }

      @

      //-----------------------------------
      The program shall continously prints "AlaMaKota" as intent. But problem is-after a few second after start program crash with:
      "The program has unexpectedly finished". If I delete msleep(1) from loop, it cause crash immediately after start.
      What the problem?

      1 Reply Last reply Reply Quote 0
      • T
        tchoninho last edited by

        Hi,

        It's a productor/consumer problem... take a look in QSemaphore/QMutex/QWaitCondition examples.

        Computer Scientist
        Belo Horizonte - Brasil
        C++ Development
        Qt Development

        1 Reply Last reply Reply Quote 0
        • M
          Mario84 last edited by

          Locking the Mutex only when writing (enqueue) isn't enough -> when reading the data (dequeue) you'll have to lock the same Mutex again, to ensure the data is never accessed by both threads at the same time.

          1 Reply Last reply Reply Quote 0
          • First post
            Last post