Summary of process threads and stack relationships

Source: Internet
Author: User

Summary of process threads and stack relationships

Suddenly think of the stack of the process and the stack of the thread. By the way, the stack of the thread is automatically allocated to the memory space of the process.

Processes and threads are the basic units for running programs that the operating system understands. The system uses this basic unit to realize the system's concurrency for applications. The difference between a process and a thread is:

In short, a program has at least one process, and a process has at least one thread.
The thread division scale is smaller than the process, making the multi-thread program highly concurrent.
In addition, the process has independent memory units during execution, and multiple threads share the memory, which greatly improves the program running efficiency.
The execution process of a thread is different from that of a process. Each Independent thread has a program running entry, sequence execution sequence, and program exit. But the thread cannot be executed independently. It must exist in the application and the application provides multiple thread execution control.
Logically, multithreading means that multiple execution parts in an application can be executed simultaneously. However, the operating system does not view multiple threads as multiple independent applications to implement process scheduling, management, and resource allocation. This is an important difference between processes and threads.

A process is a running activity of a program with certain independent functions. A process is an independent unit for the system to allocate and schedule resources.
A thread is an entity of a process. It is the basic unit for CPU scheduling and scheduling. It is smaller than a process and can run independently. the thread itself basically does not have system resources, and only has a few resources (such as program counters, a set of registers and stacks) that are essential for running ), however, it can share all resources of a process with other threads of the same process.
One thread can create and cancel another thread, and multiple threads in the same process can be concurrently executed.

 

========================================================== ================================

 

Heap:It is a space shared by everyone, divided into global heap and partial heap. The global heap is all unallocated space, and the local heap is the space allocated by the user. Heap is allocated when the operating system initializes the process. During the running process, you can also request additional heap to the system, but remember to return the heap to the operating system after it is used up. Otherwise, the memory will leak.


STACK:It is unique to a thread and stores its running status and Local Automatic variables. The stack is initialized at the beginning of the thread. the stacks of each thread are independent of each other. Therefore, the stack is thread safe. Each data member of a C ++ object also exists in the stack. Each function has its own stack, which is used to transmit parameters between functions. The operating system automatically switches the stack when switching the thread, that is, switches the SS/ESP register. Stack space does not need to be explicitly allocated or released in advanced languages.

Stack and stack differences

I. Prerequisites-Program memory allocation
The memory occupied by a C/C ++ compiled program is divided into the following parts:
1. STACK: the stack zone is automatically allocated and released by the compiler, and stores function parameter values and local variable values. The operation method is similar to the stack in the data structure.

2. Heap-generally assigned and released by the programmer. If the programmer does not release the heap, it may be recycled by the OS at the end of the program. Note that it is different from the heap in the data structure. The allocation method is similar to the linked list.

3. Global (static)-the storage of global variables and static variables is put together, and the initialized global variables and static variables are in one area, uninitialized global variables and uninitialized static variables are in another adjacent area. -The program is released by the system after it is completed.

4. Text Constant Area-constant strings are placed here. The program is released by the system.

5. program code area-stores the binary code of the function body.

Ii. Example program // main. cpp
Int A = 0; global initialization Zone
Char * P1; uninitialized globally
Main ()
{
Int B; stack
Char s [] = "ABC"; stack
Char * P2; stack
Char * P3 = "123456"; 123456/0 is in the constant zone, and P3 is on the stack.
Static int C = 0; Global (static) initialization Zone
P1 = (char *) malloc (10 );
P2 = (char *) malloc (20 );
The allocated 10-byte and 20-byte areas are in the heap area.
Strcpy (P1, "123456"); 123456/0 is placed in the constant area, and the compiler may optimize it to the "123456" that P3 points.
}Ii. Theoretical knowledge of heap and stack
2.1 Application Method
STACK:
Automatically assigned by the system. For example, declare a local variable int B in the function; the system automatically opens up space for B in the stack.
Heap:
The programmer needs to apply and specify the size. In C, the malloc Function
For example, P1 = (char *) malloc (10 );
Use the new operator in C ++
For example, P2 = (char *) malloc (10 );
But note that P1 and P2 are in the stack.

2.2
System Response after application
STACK: as long as the remaining space of the stack exceeds the applied space, the system will provide the program with memory. Otherwise, an exception will be reported, prompting stack overflow.
Heap: First, you should know that the operating system has a linked list that records idle memory addresses. When the system receives a program application, it will traverse the linked list, find the heap node with the first space greater than the requested space, delete the node from the idle node linked list, and allocate the space of the node to the program. In addition, for most systems, the size of the allocation will be recorded at the first address in the memory space, so that the delete statement in the code can correctly release the memory space. In addition, because the size of the heap node is not necessarily equal to the applied size, the system automatically places the excess part in the idle linked list.

2.3 Application size limit
STACK: in windows, a stack is a data structure extended to a low address and a continuous memory area. This statement indicates that the stack top address and the maximum stack capacity are pre-defined by the system. In Windows, the stack size is 2 MB (OR 1 MB, it is a constant determined during compilation. If the requested space exceeds the remaining space of the stack, overflow is displayed. Therefore, the space available from the stack is small.
.
Heap: the heap is a data structure extended to the high address and a non-sequential memory area. This is because the system uses the linked list to store the idle memory address, which is naturally discontinuous, And the traversal direction of the linked list is from the low address to the high address. The heap size is limited by the valid virtual memory in the computer system. It can be seen that the space obtained by the heap is flexible and large.

2.4 comparison of application efficiency:
The stack is automatically allocated by the system, which is faster. But programmers cannot control it.
The heap is the memory allocated by new, which is generally slow and prone to memory fragments. However, it is most convenient to use.
In addition, in windows, the best way is to use virtualalloc to allocate memory. Instead of heap or stack, it is to reserve a fast memory in the address space of the process, although it is the most inconvenient to use. However, it is fast and flexible.

Storage content in 2.5 heap and stack
STACK: when calling a function, the first entry to the stack is the address of the next instruction in the main function (the next executable statement in the function call statement), and then the parameters of the function, in most C compilers, parameters are written from right to left into the stack, followed by local variables in the function. Note that static variables are not included in the stack.
When the function call ends, the local variable first goes out of the stack, then the parameter, and the top pointer of the stack points to the address of the initial storage, that is, the next instruction in the main function, where the program continues to run.
Heap: Generally, the heap size is stored in one byte in the heap header. The specific content in the heap is arranged by the programmer.

2.6 comparison of access efficiency

Char S1 [] = "aaaaaaaaaaaaa ";
Char * S2 = "bbbbbbbbbbbbbbbbb ";
Aaaaaaaaaaa is assigned a value at the runtime;
Bbbbbbbbbbbbb is determined during compilation;
However, in future access, the array on the stack is faster than the string pointed to by the pointer (such as the heap.
For example, void main ()
{
Char A = 1;
Char C [] = "1234567890 ";
Char * P = "1234567890 ";
A = C [1];
A = P [1];
Return;
} The corresponding assembly code 10: A = C [1];
00401067 8A 4D F1 mov Cl, byte PTR [ebp-0Fh]
0040106a 88 4D FC mov byte PTR [ebp-4], Cl
11: A = P [1];
0040106d 8B 55 EC mov edX, dword ptr [ebp-14h]
00401070 8A 42 01 mov Al, byte PTR [edX + 1]
00401073 88 45 FC mov byte PTR [ebp-4], the first type of Al reads the elements in the string directly into the CL register, in the second type, read the pointer value to EDX.
Reading characters by EDX is obviously slow.

2.7 summary:
Stack and stack differencesWe can see from the following metaphor:
Using Stacks is like eating at a restaurant, just ordering food (sending an application), paying for it, and eating (using it). If you are full, you can leave, without having to worry about the preparation work, such as cutting and washing dishes, as well as the cleaning and tail work such as washing dishes and flushing pots, his advantage is fast, but his degree of freedom is small.
Using heap is like making your favorite dishes. It is troublesome, but it suits your taste and has a high degree of freedom.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.