码迷,mamicode.com
首页 > 编程语言 > 详细

线程_递归锁

时间:2020-03-28 23:43:26      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:class   print   线程   信号   rlock   import   pre   random   current   

#死锁:锁只能抢一次,释放后被其他人抢
from threading import Thread,Lock,current_thread
import time
class MyThread(Thread):
    def run(self):
        self.f1()
        self.f2()
    def f1(self):
        mutexA.acquire()
        print("%s 抢到A锁" %current_thread().getName())
        mutexB.acquire()
        print("%s 抢到B锁" %current_thread().getName())
        print("%s 释放B锁" %current_thread().getName())
        mutexB.release()
        print("%s 释放A锁" %current_thread().getName())
        mutexA.release()
        
    def f2(self):
        mutexB.acquire()
        print("%s 抢到B锁" %current_thread().getName())
        time.sleep(1)
        mutexA.acquire()
        print("%s 抢到A锁" %current_thread().getName())
        print("%s 释放A锁" %current_thread().getName())
        mutexA.release()
        print("%s 释放B锁" %current_thread().getName())
        mutexB.release()
        
if __name__=="__main__":
    mutexA=Lock()
    mutexB=Lock()
    for i in range(20):
        t=MyThread()
        t.start()
# ‘‘‘
# Thread-758 抢到A锁
# Thread-758 抢到B锁
# Thread-758 释放B锁
# Thread-758 释放A锁
# Thread-758 抢到B锁
# Thread-759 抢到A锁
# ‘‘‘
    
# 递归锁:锁可以抢多次,acquire一次,count加1,release一次,count减1,直到count=0,锁最终释放别其他人抢
from
threading import Thread,RLock,current_thread import time class MyThread(Thread): def run(self): self.f1() self.f2() def f1(self): mutex.acquire() print("%s 抢到锁" %current_thread().getName()) mutex.acquire() print("%s 抢到锁" %current_thread().getName()) print("%s 释放锁" %current_thread().getName()) mutex.release() print("%s 释放锁" %current_thread().getName()) mutex.release() def f2(self): mutex.acquire() print("%s 抢到锁" %current_thread().getName()) time.sleep(1) mutex.acquire() print("%s 抢到锁" %current_thread().getName()) print("%s 释放锁" %current_thread().getName()) mutex.release() print("%s 释放锁" %current_thread().getName()) mutex.release() if __name__=="__main__": mutex=RLock() for i in range(20): t=MyThread() t.start() ‘‘‘ Thread-808 抢到锁 Thread-808 抢到锁 Thread-808 释放锁 Thread-808 释放锁 Thread-810 抢到锁 Thread-810 抢到锁 Thread-810 释放锁 Thread-810 释放锁 ‘‘‘

 

#线程:信号量【锁】

from threading import Thread,current_thread,Semaphore
import time,random
sm=Semaphore(3)
def work():
    sm.acquire()
    print("target %s is running" %current_thread().getName())
    time.sleep(random.randint(1,3))
    sm.release()
    
if __name__=="__main__":
    for i in range(10):        
        t=Thread(target=work)    
        t.start()

 

线程_递归锁

标签:class   print   线程   信号   rlock   import   pre   random   current   

原文地址:https://www.cnblogs.com/hapyygril/p/12590085.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!