Multiple threads (or processes) want to execute the same specific non-reentrant program code block (called a critical section), which requires appropriate concurrency control synchronization technology. Otherwise, race conditions may occur.
Use some technical means to manage critical resources Protect and avoid confusion during shared use.
To give a simple example, our Alipay transfers ?1RBM to Mr.@王Chai. At this time, another person also transfers ?1RBM to him. At this time, he already has 1 yuan in his wallet. However, since the two accounts are entered at the same time, the non-thread synchronization system will perform the following operations:
The non-thread synchronization final withdrawal of the wallet balance is 2 yuan, which is obviously wrong. Yes, let’s take a look after adding thread synchronization:
The final wallet balance is 3 yuan. The solution here is to use locking? To solve it, then the specific What are the methods?
We can also use a more popular example to illustrate:
There is a newly built intersection. Is it suitable for this intersection? There are not many vehicles? Every time we come to this intersection, we pass it happily. But gradually more and more people know this road, but everyone passes the intersection in an orderly manner. As a result, one day There was an accident, so the person in charge of road facilities installed a traffic light. Only when the green light in this direction is on can people in this direction move forward. This is a mutual exclusion lock Some vehicles do not necessarily have to cross the intersection when they come here. Some vehicles make a U-turn here, so the people in charge of road facilities designed a U-turn lane to allow U-turn vehicles to pass without having to wait with the through vehicles. Only when the light is red can you make a U-turn. This is the read-write lock There was a fire in a nearby warehouse, and the fire truck occupied the turning lane (the occupied resources are not released, and others can pass by themselves) until the fire convoy?? ?Vehicles behind can pass normally only after passing through. This is the spin lock. This intersection is the entrance to the city. Over time, the traffic pressure has increased, and the transportation department has begun to specify regulations. Vehicles from outside the city during morning and evening peak hours Traffic is prohibited and a restricted number appears. This is to add a "condition variable" and add a buffer to relieve the pressure. Some examples may not be so accurate, such as spin locks, but this example is combined with reality The theory allows us to quickly understand the characteristics of each lock in the memory.
The above is the detailed content of Two life examples help you understand 'Thread Synchronization Principle'. For more information, please follow other related articles on the PHP Chinese website!