With the continuous development of Technology , Previous CPU There's only one core , Now there are as many as dozens of , Even a few hundred . This means that multithreaded programs allow each thread to have an exclusive CPU The core is running . Since each core is independent , Then it will be like climbing mountains with many people , There's always someone who runs fast , Everyone will arrive at the top of the mountain in a different order . If we let many people relay a batch of materials to the mountain , Then this group of people must cooperate , Otherwise the chain will fall out of the middle . Empathy , In multithreaded programs , because CPU The time slice rotation is different , Causes the thread execution order to be indeterminate ; Multi core existence , As a result, each core runs in a different order . therefore , If a resource is exclusive , Multiple threads must cooperate to execute . Like in the computer , Generally, there is only one display card , Now use multithreading to draw , If you don't control the order of each thread , It will lead to A Thread after drawing semicircle ,B The thread is outputting text , What's causing the whole screen to display is messy .
To ensure data synchronization , You should allow only one thread to access the same resource at the same time . This is about using Lock function , It will return a thread lock instance . The method of calling it in thread code acquire To apply for the use of resources , If this thread successfully applies for access , that Lock The object will lock , Other threads can no longer access this resource , Only threads call release Method before other threads can access it .
First of all, use the case of no lock to execute , Look at the results , The code is as follows ：
count = 30
lock = Lock() # Create global lock object
# Define thread work functions </