std::vector, thread-safety, multi-threading

后端 未结 3 1046
傲寒
傲寒 2020-11-27 08:21

I am using std::vector as shared data in a multi-threaded application. I encapsulate the thread inside a class, e.g.,

class ABC {
public:
    double a, b, c         


        
相关标签:
3条回答
  • 2020-11-27 08:24

    Actually, it is absolutely pointless to state X is or is not thread-safe! You need to qualify for what kind of uses. For example, hardly any class will be "thread-safe" when it is somehow used in one thread and destroyed in another.

    That said, the statement that std::vector<T> is not thread- safe, independent of how often it is repeated, is wrong. However, it seems most people neither understand nor appreciate the thread-safety guarantees given. std::vector<T> is thread-safe in the following sense:

    • You can read a vector object from multiple threads simultaneously.
    • If there is one thread changing a vector object, there shall be neither concurrent readers or writers.
    • Accesses to a vector object don't interfere with other vector objects.

    This applies to vector structure itself. Accesses to contained object are bound to whatever rules are imposed on them. These are apparently not the thread-safety guarantees many people have in mind but anything stronger won't work with the container interface.

    0 讨论(0)
  • 2020-11-27 08:36

    You call ptrVector->size() without locking it first. This could easily be the cause of your problems. Make sure to lock your vector before any reads or writes.

    0 讨论(0)
  • 2020-11-27 08:46

    Maybe you could use this instead?

    concurrent_vector... from the Intel Threading Building Blocks

    https://software.intel.com/en-us/node/467758

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