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

前端 未结 4 1898
终归单人心
终归单人心 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 18:01

    In answer to your simplified question:

    ConcurrentQueue queue = null;
    
    Parallel.Invoke(
        () => queue = new ConcurrentQueue(),
        () => queue?.Enqueue(5));
    

    It is definitely possible that your code could try to call queue.Enqueue(5) before queue has a value, but it isn't anything you could protect against from within the constructor of Queue. queue won't actually be assigned a reference to the new instance until the constructor completes.

提交回复
热议问题