gpt4 book ai didi

c# - 如果我在锁定期间修改引用字段,它是否需要可变?

转载 作者:行者123 更新时间:2023-11-30 21:13:49 24 4
gpt4 key购买 nike

考虑以下发生在后台线程(“线程 B”)中的代码:

List<T> invocationQueueCopy;
lock (invocationQueue)
{
invocationQueueCopy = invocationQueue;
invocationQueue = new List<T>();
}

在另一个线程(“线程 A”)中,我在添加之前简单地锁定了“invocationQueue”:

lock (invocationQueue)
{
invocationQueue.Add(args);
}

我已经读到引用分配是原子的,但是否会发生“线程 A”在收到锁后最终写入旧列表(“线程 B”中替换的列表)?我读过其他暗示它可以的答案,如果引用的值存储在“线程 A”上的寄存器中,那么它不会知道“线程 B”修改了类中的值。如果是这样,声明“invocationQueue”volatile 会阻止这种情况吗?

注意事项:

  • 我知道我可以克隆然后清除列表。
  • 我知道我可以有一个单独的锁列表的对象。

但除非必要,否则我宁愿不做这些事情。

提前致谢。

编辑:

只是从 Adam 的评论中澄清一下:invocationQueue 是一个私有(private)字段,它是在此类内部创建的,从不暴露给外界,因此除了这两个方法之外没有任何东西可以锁定它。

最佳答案

编辑:您的解决方案将起作用。锁创建一个 full fence所以任何缓存都被阻止,基本上意味着您将始终获得列表引用的最新值。正如评论中所建议的,唯一的事情是您应该锁定中性对象,而不是列表本身。

以下是错误的!!但无论如何我还是把它放在这里是为了展示 fu*** 硬线程可能是多么...事实是以下推理被锁创建一个完整的栅栏这一事实打败了。

Yeah, it can happen so don't do it that way.

It won't get better even if you did the lock into a readonly whatever object.

See what might happen (although most of the time it WON'T happen).

ThreadA and ThreadB are executing on different processors, each one with its own cache memory which holds the reference to incovationQueue.

  • ThreadB locks invocationQueue, the lock is done to a reference which is taken for the cache of processor1, not to a variable name.
  • ThreadB copies the invocationQueue.
  • ThreadA locks invocationQueue, the lock is done to a reference which is taken for the cache on processor2 and which, in this moment is the same as the one in processor1, and starts waiting.
  • ThreadB creates a new List and assigns it to the invocationQueue, the cache in the processor1 is updated but since the variable is NOT volatile that's all that happens.
  • ThreadA enters the lock and gets the reference from his cache, which points to the old reference, therefore you end up adding the variable to the old list.

So you need to make the list volatile AND use the lock if you're going to be playing with the reference itself.

关于c# - 如果我在锁定期间修改引用字段,它是否需要可变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6634494/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com