Do I need to protect read access to an STL container in a multithreading environment?

前端 未结 8 1735
逝去的感伤
逝去的感伤 2020-11-29 10:01

I have one std::list<> container and these threads:

  • One writer thread which adds elements indefinitely.

  • One reader/writer thread which re

相关标签:
8条回答
  • 2020-11-29 10:08

    Yes. I would suggest wrapping your STL library with a class that enforces serial access. Or find a similar class that's already been debugged.

    0 讨论(0)
  • 2020-11-29 10:09

    The STL in VC++ version 6 is not thread-safe, see this recent question. So it seems your question is a bit irrelevant. Even if you did everything right, you may still have problems.

    0 讨论(0)
  • 2020-11-29 10:13

    Checkout the concurrent containers provided by Intel's Open Source Threading Building Blocks library. Look under "Container Snippets" on the Code Samples page for some examples. They have concurrent / thread-safe containers for vectors, hash maps and queues.

    0 讨论(0)
  • 2020-11-29 10:14

    Yes, the read threads will need some sort of mutex control, otherwise the write will change things from under it.

    A reader/writer mutex should be enough. But strictly speaking this is an implmentation-specific issue. It's possible that an implementation may have mutable members even in const objects that are read-only in your code.

    0 讨论(0)
  • 2020-11-29 10:21

    I'm going to say no. In this case.

    Without a mutex, what you might find is that the size() returns the wrong value occasionally, as items are added or removed. If this is acceptable to you, go for it.

    however, if you need the accurate size of the list when the reader needs to know it, you'll have to put a critical section around every size call in addition to the one you have around the add and erase calls.

    PS. VC6 size() simply returns the _Size internal member, so not having a mutex won't be a problem with your particular implementation, except that it might return 1 when a second element is being added, or vice-versa.

    PPS. someone mentioned a RW lock, this is a good thing, especially if you're tempted to access the list objects later. Change your mutex to a Boost::shared_mutex would be beneficial then. However no mutex whatsoever is needed if all you're calling is size().

    0 讨论(0)
  • 2020-11-29 10:22

    I don't believe the STL containers are thread-safe, as there isn't a good way to handle threads cross-platform. The call to size() is simple, but it still needs to be protected.

    This sounds like a great place to use read-write locks.

    0 讨论(0)
提交回复
热议问题