Beginner: Thread/sleep/Q



  • 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?



  • Hi,

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



  • 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.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.