保护数据安全性:
lock = threading.RLock()
def Func():
lock.acquire()
#局部变量默认不能修改全局变量
global gl_num
gl_num += 1
time.sleep(1)
print(gl_num)
lock.release()
for i in range(10):
t = threading.Thread(target=Func)
t.start()
同时分配锁给多个线程:
#!/usr/bin/python
#_*_ coding:UTF-8 _*_
import threading
import time
gl_num = 0
bsm = threading.BoundedSemaphore(4)
def Func():
bsm.acquire()
#局部变量默认不能修改全局变量
global gl_num
gl_num += 1
time.sleep(1)
print(gl_num)
bsm.release()
for i in range(10):
t = threading.Thread(target=Func)
t.start()
执行结果:
4
5
6
7
8
8
10
10
10
10