Why do threads share the heap space?

前端 未结 8 784
时光取名叫无心
时光取名叫无心 2020-12-23 10:12

Threads each have their own stack, but they share a common heap.

Its clear to everyone that stack is for local/method variables & heap is for instance/class vari

8条回答
  •  长情又很酷
    2020-12-23 11:04

    In many languages/runtimes the stack is (among other) used for keep function/method parameters and variables. If thread shared a stack, things would get really messy.

    void MyFunc(int a) // Stored on the stack
    {
       int b; // Stored on the stack
    }
    

    When the call to 'MyFunc' is done, the stacked is popped and a and b is no longer on the stack. Because threads dont share stacks, there is no threading issue for the variables a and b.

    Because of the nature of the stack (pushing/popping) its not really suited for keeping 'long term' state or shared state across function calls. Like this:

    int globalValue; // stored on the heap
    
    void Foo() 
    {
       int b = globalValue; // Gets the current value of globalValue
    
       globalValue = 10;
    }
    
    void Bar() // Stored on the stack
    {
       int b = globalValue; // Gets the current value of globalValue
    
       globalValue = 20;
    }
    
    
    void main()
    {
       globalValue = 0;
       Foo();
       // globalValue is now 10
       Bar();
       // globalValue is now 20
    }
    

提交回复
热议问题