线程本地存储和本地方法变量 [英] Thread Local Storage and local method variables

查看:77
本文介绍了线程本地存储和本地方法变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在c#中,每个线程都有自己的堆栈空间.

In c#, each thread has its own stack space.

如果是这种情况,为什么以下代码不是线程安全的? (据指出,此代码 在此帖子上是线程安全的:在C#中锁定

If this is the case, why is the following code not thread-safe? (It is stated that this code is thread-safe on this post: Locking in C#

class Foo 
{ 
    private int count = 0; 
    public void TrySomething()     
    { 
        count++; 
    } 
} 

由于count是一个int(堆栈变量),该值肯定会被隔离到单个线程的单独堆栈中,因此是线程安全的吗?

As count is an int (stack variable), surely this value would be isolated to an individual thread, on its own stack, and therefore thread-safe?

我可能在这里丢失了一些东西,但是我不明白如果不是基于线程的基于堆栈的变量,线程本地存储中到底有什么?

I am probably missing something here, but I dont understand what is actually in Thread Local Storage if not stack-based variables for the thread?

还有,本地声明的变量呢?

Also, what about locally-declared variables:

class Foo 
{ 
    public void TrySomething(object myObj)     
    { 
       var localVariable = new object();
       localVariable = myObj;
    } 
} 

这里对局部变量有什么影响?它仍然是基于堆的吗?它是线程安全的吗?

What are the implications here on the local variable? Is it still heap-based? Is it thread-safe?

推荐答案

Count是Foo类的成员变量.由于Foo是引用类型,因此它存储在堆中而不是堆栈中.

Count is a member variable of the class Foo. As Foo is a reference type it is stored on the heap not the stack.

如果仅创建1个Foo对象,并允许两个单独的线程调用TrySomething()方法,则它们都将在同一对象(存储在堆上)上调用该方法,并且两者都将尝试递增同一个成员,因为它是同一对象的一部分. (请参见Darin的示例代码)

If you created only 1 Foo object and allowed two separate threads to call the TrySomething() method, they would both be calling the method on the same object (stored on the heap), and both would attempt to increment the same member as it's part of that same object. (See Darin's sample code)

结构和类之间的区别不在于它们是存储在堆中还是堆栈中.这是一个普遍的误解.将类视为指向堆上存储的指针.可以将结构视为存储在本地的直接值.从一个非常简单的层面上讲,这确实意味着结构通常存储在堆栈中,当然并非在所有情况下都如本例所示.

The difference between structs and classes is not whether they are stored on the heap or the stack. This is a common misconception. Think of classes as pointers to storage on the heap. Think of structs as direct values being stored locally. At a very simple level, this does mean that structs are often stored on the stack, it's certainly not true in all cases as this example shows.

这篇关于线程本地存储和本地方法变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆