这是初始化 [ThreadStatic] 的线程安全方法吗?

发布于 2024-07-26 00:54:47 字数 211 浏览 6 评论 0原文

[ThreadStatic]
private static Foo _foo;

public static Foo CurrentFoo {
   get {
     if (_foo == null) {
         _foo = new Foo();
     }
     return _foo;
   }
}

前面的代码线程安全吗? 或者我们需要锁定该方法吗?

[ThreadStatic]
private static Foo _foo;

public static Foo CurrentFoo {
   get {
     if (_foo == null) {
         _foo = new Foo();
     }
     return _foo;
   }
}

Is the previous code thread safe? Or do we need to lock the method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥醉 2024-08-02 00:54:47

如果是 ThreadStatic,则每个线程只有一份副本。 因此,根据定义,它是线程安全的。

此博客提供了一些有关 ThreadStatic 的好信息.

If its ThreadStatic there's one copy per thread. So, by definition, its thread safe.

This blog has some good info on ThreadStatic.

心的憧憬 2024-08-02 00:54:47

[ThreadStatic] 是线程本地存储的编译器/语言魔法。 换句话说,它绑定到线程,所以即使有上下文切换也没关系,因为没有其他线程可以直接访问它。

A [ThreadStatic] is compiler/language magic for thread local storage. In other words, it is bound to the thread, so even if there is a context switch it doesn't matter because no other thread can access it directly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文