Is there any way to check if an iterator is valid?

后端 未结 5 746
面向向阳花
面向向阳花 2021-01-06 15:21

For two threads manipulating a container map for example, what the correct way to test whether an iterator still valid (for performance reason) ?
Or would be of only in

相关标签:
5条回答
  • 2021-01-06 15:46

    If you implement a reader/writer solution, then you can have the writer set a flag that invalidates all the iterators of the readers.

    http://en.wikipedia.org/wiki/Readers-writer_lock

    I would not try to write to the map without synchronization, as Josh and Paul Tomblin mentioned.

    0 讨论(0)
  • 2021-01-06 15:50

    If your STL does not offer a thread safe std::map, Intel's TBB offers a thread-safe concurrent_hash_map (pages 60 and 68).

    Putting thread safety issues aside, std::map does guarantee that deletions do not invalidate iterators other than the one being deleted. Unfortunately there isn't a is_iterator_valid() method to validate iterators that you hold.

    It may be possible to implement something like hazard pointers, and TBB has some workarounds to the problem as well.

    0 讨论(0)
  • 2021-01-06 15:58

    If you know that one of the threads is only going to read the map while the other might be manipulating it, the simplest solution is to have the read-only thread clone the map and iterate over the clone.

    (Caveat: I know Java's collection classes a lot better than I know STL, but this is how I'd do it in Java.)

    0 讨论(0)
  • 2021-01-06 16:04

    Even you were able to tell if a pointer were valid, it would not solve your problem. You are sharing a single resource with no exlusivelty guarentee. Here is why it would fail.

    It would fail in this thread sequence:

    Thread0................................Thread1

    Get iterator->it0

    check that it0 is valid

    .............................................Get Iterator->it1

    .............................................Check that it1 is valid.

    Erase (it0)

    .............................................Erase (it1)

    You can add a semaphore to access the shared resource.

    0 讨论(0)
  • 2021-01-06 16:07

    std::maps are not at all thread-safe. You'll end up with much worse problems than invalidated iterators, if you have more than one thread at a time modifying the same map. I don't even think you have a guarantee that you can read anything out of a map while it's being modified by another thread.

    Some pages on the STL and threading:

    • MSDN
    • SGI
    • GCC
    0 讨论(0)
提交回复
热议问题