#coding: Utf-8 ' thread lock ' import threadingimport timenum = 0 #全局变量num2 = 0def runs (): time.sleep (1) global num # To make a change to a global variable inside a function, you need to declare global num2 lock.acquire () # Locks during operation to prevent other threads from adding 1 to the NUM variable at the same time, ensuring that the data is at the same time ensured that only one thread makes changes to it, otherwise the data is incorrect num += 1 lock.acquire () #再获得一把锁 num2 += 2 #在这里一个线程获得了2把锁, so need to release 2 times lock.release () # release 1th lock, add 1 after release lock, Only after releasing the next thread will start the operation of the NUM process, do not release the word otherwise will be occupied by the thread, causing the program to continue to execute, has been in a blocking state time.sleep (0.01) lock.release () # release 2nd lock, add after 2 release lock time.sleep (0.01) print ("%s" % num) lock = threading. Rlock () #RLock是允许同时获得好几把锁增加一把锁, if you only need a lock, then use threading. Lock () can # start 100 threads, which means these 100The thread runs the RUSN function at the same time For i in range ($): t = threading. Thread (Target=runs,) t.start ()
This article is from the "Operation and maintenance of AC Q Group: 223843163" blog, please be sure to keep this source http://freshair.blog.51cto.com/8272891/1898706
Python multi-thread lock two (one thread at a time acquires 2 locks)