Threadsafe Vector class for C++

前端 未结 6 633
一整个雨季
一整个雨季 2020-12-03 03:58

Does anyone know a quick and dirty threadsafe vector class for c++? I am multithreading some code, and I believe the problem I have is related to the way the vectors are us

6条回答
  •  失恋的感觉
    2020-12-03 04:22

    I forget who discussed this, but one strategy for making a thread-safe container is as follows:

    1. All your class's public methods must lock the vector, and must return a boolean for if they succeeded (and they might not succeed!). So instead of using f = myvec[i], use if (myvec.tryGet(i, &f)) {...} and implement the class accordingly.
    2. Do not provide a count method. Users must use iterators to traverse the vector.

    Note: Be careful with iteration. You must be clever about maintaining a never-shrinking vector with bounds-checking iterators or you might have code that has buffer-overflow type errors.

    The lame and easy way to provide a "thread-safe" vector is to just take a standard vector and lock the vector on every method. But if you do this, you could still end up with broken code (e.g. a loop that iterates from 0 to vec.count may have count change while it is iterating).

    A 2nd means of providing "thread-safe" containers is to create immutable containers (every method returns a new container. This was definitely discussed by Eric Lippert. It's C#, but easily translates to C++ code, mostly. You'll still need to lock the container when you use it, but all the scary issues involving buffer overflows when iterators break and whatnot go away. Implementing an immutable container is probably relatively 2nd nature to those who are experienced with functional programming.

提交回复
热议问题