python-线程互斥锁与递归锁

1.线程跟进程里的互斥锁一样:

     将多个并发任务的部分代码(只涉及修改共享数据的代码,编程串行线程或进程操作)

     加锁可以保证多个进程修改同一数据,同一时间只能只要一个任务可以进行修改,这样可以保证数据的安全性,单牺牲了速度

 

from threading import thread,lock

import time

mutex=lock()

x=100

def task():

    global x

    mutex.acquire()

    temp=x

    time.sleep(1)

    x=temp-1

    mutex.release()



if __name__ =='__main__':

    t_l=[]

    start=time.time()

    for i in tange():

       t=thread(target=task)

        t_l.append(t)

        t.start()
    for t in t_l:

        t.join()

    shop=time.time()

    print(x,stop-start)

 

递归锁:互斥锁一旦运用在多个修改共享数据的时候,会出现锁死的情况,所以这个时候需要用到递归锁

 

            特点:可以连续的acquire()

from threading import Thread,Lock,active_count,RLock
import time

# mutexA=Lock()
# mutexB=Lock()
obj=RLock() #递归锁的特点:可以连续的acquire
mutexA=obj
mutexB=obj

class Mythread(Thread):
    def run(self):
        self.f1()
        self.f2()

    def f1(self):
        mutexA.acquire()
        print('%s 拿到A锁' %self.name)

        mutexB.acquire()
        print('%s 拿到B锁' %self.name)
        mutexB.release()

        mutexA.release()

    def f2(self):
        mutexB.acquire()
        print('%s 拿到B锁' %self.name)
        time.sleep(1)

        mutexA.acquire()
        print('%s 拿到A锁' %self.name)
        mutexA.release()

        mutexB.release()

if __name__ == '__main__':
    for i in range(10):
        t=Mythread()
        t.start()
    print(active_count())           #统计当前线程数#递归锁的特点:可以连续的acquire
mutexA=obj
mutexB=obj

class Mythread(Thread):
    def run(self):
        self.f1()
        self.f2()

    def f1(self):
        mutexA.acquire()
        print('%s 拿到A锁' %self.name)

        mutexB.acquire()
        print('%s 拿到B锁' %self.name)
        mutexB.release()

        mutexA.release()

    def f2(self):
        mutexB.acquire()
        print('%s 拿到B锁' %self.name)
        time.sleep(1)

        mutexA.acquire()
        print('%s 拿到A锁' %self.name)
        mutexA.release()

        mutexB.release()

if __name__ == '__main__':
    for i in range(10):
        t=Mythread()
        t.start()
    print(active_count())           #统计当前线程数

 

 

 

           

posted @ 2018-07-15 10:48  Marcki  阅读(292)  评论(0编辑  收藏  举报