python-线程锁_互斥&递归

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值