In this article, let's look at what a Python thread lock is. Learn about the Python thread lock and what the thread lock can do in Python programming.
Thread lock (Mutex mutex)
A process can start multiple threads, multiple threads share the memory space of the parent process, which means that each thread can access the same data, at this time, if 2 threads simultaneously to modify the same data, what will happen?
Use of Locks:
Create a lock
Mutex = Threading. Lock ()
Lock
Mutex.acquire ([timeout])
Release
Mutex.release ()
Import Timeimport threadingdef addnum (): global num #在每个线程中都获取这个全局变量 print ('--get num: ', num) time.sleep ( 1) num -=1 #对此公共变量进行-1 Operation num = #设定一个共享变量thread_list = []for i in range]: t = Threading. Thread (Target=addnum) T.start () thread_list.append (t) for T in Thread_list: #等待所有线程执行完毕 t.join () Print (' final num: ', num)
Normally, this num result should be 0, but in Python 2.7 run more than a few times, you will find that the final printout of the NUM result is not always 0, why each run the result is different? Ha, very simple, if you have a A, a, two threads, at this time to the NUM to reduce the 1 operation, because 2 threads are concurrently running concurrently, so 2 threads are likely to take the num=100 this initial variable to the CPU to calculate, when a thread to end the result is 99, But at this point the result of the B-thread operation is also 99, two threads at the same time the result of the CPU operation is assigned to the NUM variable, the result is 99. What about that? It is very simple that each thread will modify the data in order to avoid having to modify it when it is not finished, so you can add a lock to the data so that other threads will have to wait for you to modify the data and release the lock before accessing the data.
Note: Do not run on the 3.x, do not know why, the results on 3.x is always correct, may be automatically added lock