How do two or more threads share memory on the heap that they have allocated?

前端 未结 5 561
春和景丽
春和景丽 2020-12-28 08:09

As the title says, how do two or more threads share memory on the heap that they have allocated? I\'ve been thinking about it and I can\'t figure out how they can do it. Her

5条回答
  •  长发绾君心
    2020-12-28 08:48

    My interpretation of your question: How can thread A get to know a pointer to the memory B is using? How can they exchange data?

    Answer: They usually start with a common pointer to a common memory area. That allows them to exchange other data including pointers to other data with each other.

    Example:

    1. Main thread allocates some shared memory and stores its location in p
    2. Main thread starts two worker threads, passing the pointer p to them
    3. The workers can now use p and work on the data pointed to by p

    And in a real language (C#) it looks like this:

    //start function ThreadProc and pass someData to it
    new Thread(ThreadProc).Start(someData)
    

    Threads usually do not access each others stack. Everything starts from one pointer passed to the thread procedure.


    Creating a thread is an OS function. It works like this:

    1. The application calls the OS using the standard ABI/API
    2. The OS allocates stack memory and internal data structures
    3. The OS "forges" the first stack frame: It sets the instruction pointer to ThreadProc and "pushes" someData onto the stack. I say "forge" because this first stack frame does not arise naturally but is created by the OS artificially.
    4. The OS schedules the thread. ThreadProc does not know it has been setup on a fresh stack. All it knows is that someData is at the usual stack position where it would expect it.

    And that is how someData arrives in ThreadProc. This is the way the first, initial data item is shared. Steps 1-3 are executed synchronously by the parent thread. 4 happens on the child thread.

提交回复
热议问题