Write/read to the same object, multiThreading



  • I have developed a QT application that connects to two micro-controllers (two threads), and whenever data are received from the serial ports
    each thread emit a signal to update the value of certain objects (all of them are QString) in the GUI class. now the thing is that I need to write the latest values of these data on a single file every 20 ms from the GUI class. I have done all that and it seems that its working fine, but what if the GUI class wanted to
    write a value of these objects to the file and at the same time one of the threads was updating the value of that same object??
    how can I address this problem.....or is it already covered by QT

    thanks in advance

    this is an example of what I am doing:

    @
    Class A{

    void dataReceived(QByteArray a){
    QString s = a.at[1];
    emit updateGUI(s);
    }
    }

    Class GUI{
    ......
    QString ss;

    void updateGUI(QString s){
    ss = s;
    }

    void writeToFile(){

    fileWriter->writeToFile(ss);
    }

    }
    @

    what if writeToFile() and updateGUI were called at the same time, then one thread will update the value of ss where the other will read the value of ss...is
    that ok?

    [EDIT: code formatting, please wrap in @-tags, Volker]



  • I think that you need a QMutex in Class GUI.
    "QMutex doc":http://doc.qt.nokia.com/latest/qmutex.html
    Read a link - there is example. Read also about QMutexLocker.



  • thank you for your reply, but how to use is? one of the threads is always writing(so it only calls updateGUI) where the other
    is always reading the object ss (so it just calls writeToFile())

    so how to give the writing more priority than the reading of the object NOT the functions. the other
    thing is one of the threads is the GUI thread (will let go to sleep??)



  • I would try something like this(but I don't know for a 100% that is correct):
    in class GUI add a member:
    @
    Class GUI{
    ……
    // add mutex
    QMutex mutex;
    QString ss;

    void updateGUI(QString s){
    // turn on mutex
    QMutexLocker lock( &mutex );
    ss = s;
    }

    void writeToFile(){
    // turn on mutex
    QMutexLocker lock( &mutex);
    fileWriter->writeToFile(ss);
    }

    }
    @

    I think that you will have a guarantee that only one method can work with ss on the same time.



  • thank you very much you
    but don't I need to unlock the mutex after I finish?



  • A QMutexLocker will unlock a mutex when he will be destroyed.
    "QMutexLocker doc":http://doc.qt.nokia.com/latest/qmutexlocker.html#details



  • another option may be "QReadWriteLocker":http://doc.qt.nokia.com/4.7/qreadwritelock.html if this is your "problem":http://en.wikipedia.org/wiki/Readers-writers_problem


Log in to reply
 

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