Based on multi-thread concurrency - why do multi-threads need to lock

1. Private and shared resources between threads

1. Private:
thread stack, registers, program registers

2. Sharing:
heap, address space, global variables, static variables

Second, the thread reads and writes the memory data process

1. Read
1) Copy the memory content to the CPU register. load

2. Write
1) Copy the contents of memory to CPU registers. load
2) Increase the value in the CPU. increment
3) Store the new value in memory. store

3. Copy the memory content to the CPU register
1) Copy the memory according to the set alignment byte (the minimum value of a single copy).
2) Due to system and CPU architecture optimization, etc., the minimum value of a single copy may be much larger than this value, but the memory is guaranteed to be continuous.

3. Why do you need to lock

1. Data race (data race)
1) When multiple threads access their shared resources (heap, global variables, etc.), locks (mutual exclusion locks, read-write locks, recursive locks, etc.) are required, otherwise there may be registers and memory data Inconsistent.
Note: The creation of a heap object is divided into allocation of memory, initialization, pointer to the memory, pay attention to the fine-grained lock.
2) Thread private resources do not need to be locked.

2. The sub-steps of different threads have sequential relevance
1) Example:

int a = 0;

//Thread1
a = 1;

//Thread2
int b = 10/a;

That is, thread 2 must wait for thread 1 to assign a value of 1 to the variable a before it can divide a.
Note: It is the usage scenario of condition variable (std::condition_variable).
2) The order of code
is not equal to the order of program execution because the current CPU and compiler will try to optimize the code in various ways, and sometimes they may execute the code specified by the programmer when writing the program in order to optimize performance caused by disruption.

//Thread1
a = 1;
b = 2;

Code "b=2;" may run before "a=1".

If there are mistakes or deficiencies, welcome to comment and point out! Creation is not easy, please indicate the source for reprinting. If it is helpful, remember to like and follow (⊙o⊙)
For more content, please follow my personal blog: https://blog.csdn.net/qq_43148810

Guess you like

Origin blog.csdn.net/qq_43148810/article/details/128815249