Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Beginner: Thread/sleep/Q
Forum Updated to NodeBB v4.3 + New Features

Beginner: Thread/sleep/Q

Scheduled Pinned Locked Moved General and Desktop
3 Posts 3 Posters 2.5k Views 1 Watching
  • 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 Offline
    G Offline
    ginar
    wrote on 24 Apr 2013, 21:37 last edited by
    #1

    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
    0
    • T Offline
      T Offline
      tchoninho
      wrote on 24 Apr 2013, 22:00 last edited by
      #2

      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
      0
      • M Offline
        M Offline
        Mario84
        wrote on 25 Apr 2013, 07:22 last edited by
        #3

        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
        0

        3/3

        25 Apr 2013, 07:22

        • Login

        • Login or register to search.
        3 out of 3
        • First post
          3/3
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • Users
        • Groups
        • Search
        • Get Qt Extensions
        • Unsolved