python之迭代锁与信号量

如果现在需要在多处加锁大于等于2的时候 因为计算机比较笨,当他锁上一把锁的时候又所理一把锁,等他来开锁的时候他不知道用哪把钥匙来开锁,

所以这个时候我们需要把把平常的锁变为迭代锁

eg:

import threading
import time

local = threading.RLock()
# 迭代加锁首先生成实例
def run(name):
    global num
    local.acquire()  # 上锁
    num += 1
    run2(num)
    local.release()  # 解锁
    print(threading.active_count())

def run2(num):
    local.acquire()
    num += 1
    run3(num)
    local.release()

def run3(num):
    local.acquire()
    num+=1
    local.release()

num = 0
py_res = []
for i in range(50):
    t = threading.Thread(target=run,args=('t%s'%i,))
    py_res.append(t)
    t.start()


for i in py_res:
    i.join()

print("num : %s"% num)

型号量可以控制同线程的个数,和锁的用法一样

import threading
import time
senm = threading.BoundedSemaphore(5)
def run(num):
    senm.acquire()  # 上锁
    time.sleep(2)
    print('run the thread %s' % num)
    senm.release()  # 解锁

for i in range(50):
    t = threading.Thread(target=run, args=('%s' % i,))
    t.start()
    print(threading.active_count())

while threading.active_count() != 1:
    pass
else:
    print('is done')

 信号量:event

标志位 :set,设置标志位 clear 设置标志位,wait 等带标志位,is_set 判断是否设置了标志

下面是一个红绿灯的程序,实现红灯停绿灯行

import threading
import time
event = threading.Event()
# red is have flag or no

def light():
    count = 0
    while True:
        if count > 5 and count <= 10:
            print('red')
            event.set()
        elif count > 10:
            print('green')
            event.clear()
            count = 0
        else:
            print('in the else')

        time.sleep(1)
        count += 1
def car(name):
    while True:
        if event.is_set():
            print('the %s is runing...' % name)
            time.sleep(1)
        else:
            print('%s is wait...' % name)
            event.wait()


t1 = threading.Thread(target=light)
t1.start()
t2 = threading.Thread(target=car, args=('tesla', ))
t2.start()

 

posted @ 2018-12-31 17:47  晴晴小可爱的小弟  阅读(249)  评论(0编辑  收藏  举报