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

后端 未结 3 1063
傲寒
傲寒 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 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 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.

提交回复
热议问题