python-互斥锁:
import threading,time
def run(n):
lock.acquire()
global num
num +=1
time.sleep(1)
lock.release()
lock = threading.Lock()################################互斥锁
num = 0
t_objs = [] ###########################################存线程实例
for i in range(50):
t = threading.Thread(target=run,args=("t-%s" %i ,))
t.start()
t_objs.append(t)
for t in t_objs: #####################################循环线程实例列表,等待所有线程执行完毕
t.join()
print("----------all threads has finished...",threading.current_thread(),threading.active_count())
print("num:",num)
递归锁:
import threading, time
def run1():
print("in run1")
lock.acquire()
global num
num += 1
lock.release()
return num
def run2():
print("in run2")
lock.acquire()
global num2
num2 += 1
lock.release()
return num2
def run3():
print('in run3')
lock.acquire()
res = run1()
res2 = run2()
lock.release()
print(res, res2)
num, num2 = 0, 0
lock = threading.RLock()##############################生成递归锁
for i in range(10):
t = threading.Thread(target=run3)
t.start()
while threading.active_count() != 1:
print(threading.active_count())
else:
print('----all threads done---')
print(num, num2)