Thread-safe vector: Is this implementation thread-safe?

前端 未结 7 1923
梦毁少年i
梦毁少年i 2021-01-16 13:22

I have a question regarding the term thread-safety. Let me give an example:

#include 
#include 

/// A thread-safe vector
class Th         


        
7条回答
  •  终归单人心
    2021-01-16 14:07

    We have an on-going internal team discussion about the meaning of thread-safety. Slavas comment "Though length() is technically "thread safe" in reality it is not" boils it down to the ambivalent essence. Probably, it is impossible to answer my simple question with "yes" or "no"?

    Here, is my view: Thread-safety only requires clean semantics regarding PARALLEL execution of its operations. The class ThreadSafeVector is thread-safe because its functions guarantee the following for parallel execution of its operations:

    • atomicity: interleaving threads will not result in an inconsistent state (because of locking)
    • visibility: state is propagated to be seen by other threads (because of the memory-barriers induced by mutex-locking)

    Calling a class thread-safe does not require that any possible aggregated usage of it has to be thread-safe on its own, i.e. serial execution of methods on the class does not have to be thread-safe. Example:

    if (a.length() == 0) a.add(42);
    

    Of course this line is not thread-safe because it's not atomic on its own and the class does not even provide "tools" to do something like this. But just because I can construct a non-thread-safe sequence from thread-safe operations, it does not mean that the thread-safe operations are really not thread-safe.

提交回复
热议问题