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

前端 未结 4 1899
终归单人心
终归单人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 18:01

    Lazy is a very good choice for Thread-Safe Initialization. I think it should be left to the consumer to provide that:

    var queue = new Lazy>(() => new ThreadSafeQueue());
    
    Parallel.For(0, 10000, i =>
    {
    
        else if (i % 2 == 0)
            queue.Value.Enqueue(i);
        else
        {
            int item = -1;
            if (queue.Value.TryDequeue(out item) == true)
                Console.WriteLine(item);
        }
    });
    

提交回复
热议问题