Should thread-safe class have a memory barrier at the end of its constructor?

前端 未结 4 1897
终归单人心
终归单人心 2020-12-03 17:08

When implementing a class intended to be thread-safe, should I include a memory barrier at the end of its constructor, in order to ensure that any internal structures have c

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-03 17:47

    No, you don't need memory barrier in the constructor. Your assumption, even though demonstrating some creative thought - is wrong. No thread can get a half backed instance of queue. The new reference is "visible" to the other threads only when the initialization is done. Suppose thread_1 is the first thread to initialize queue - it goes through the ctor code, but queue's reference in the main stack is still null! only when thread_1 exists the constructor code it assigns the reference.

    See comments below and OP elaborated question.

提交回复
热议问题