Qt Forum

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

    Update: Forum Guidelines & Code of Conduct

    Locking of semi-read-only QVector

    General and Desktop
    3
    5
    3226
    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.
    • U
      usamytch last edited by

      Good day, colleagues!

      Suppose I have 2 threads and QVector<double> with fixed size, initialized as QVector<double> (fixed_size). First thread consequently fills this QVector with data. Second thread only reads this QVector and it's guaranteed that second thread reads only elements, which are already processed by the first thread. For example, if second thread reads vector.at(0), it's guaranteed that vector.at(0) is filled by the first thread and will not change anymore.

      The question is shoud I lock QVector with QMutex or not?

      1 Reply Last reply Reply Quote 0
      • G
        giesbert last edited by

        if you don't change the size anymore, it should be save.

        But it's saver to lock ;-)

        If it's guaranteed that the vector will never be resized, it should work.

        Nokia Certified Qt Specialist.
        Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

        1 Reply Last reply Reply Quote 0
        • Z
          ZapB last edited by

          As Gerolf said as long as you do not resize the vector (or call other methods that can change the memory layout such as reserve()) and you are sure that you are only reading from indexes that are not being written to at the same time (e.g. by using semaphores) it should be safe (I think) ;-).

          Nokia Certified Qt Specialist
          Interested in hearing about Qt related work

          1 Reply Last reply Reply Quote 0
          • U
            usamytch last edited by

            Thank you for the answers!

            1 Reply Last reply Reply Quote 0
            • Z
              ZapB last edited by

              No problem. Sounds like you could be a potential user of "this class":http://qt.gitorious.org/qt/qt/merge_requests/2364 that I wrote. I have a small wrapper around this class that makes it into a thread-safe container for the producer-consumer pattern.

              Nokia Certified Qt Specialist
              Interested in hearing about Qt related work

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