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

前端 未结 8 1789
逝去的感伤
逝去的感伤 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: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().

提交回复
热议问题