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

python Lock、RLock

时间:2019-07-06 13:01:45      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:注意   多次   release   color   lease   glob   star   desc   add   

Lock: 只能acquire一次,下一次acquire必须release后才能,不然会造成死锁

from threading import Lock

total = 0
lock = Lock()
def add():
    #1. dosomething1
    #2. io操作
    # 1. dosomething3
    global lock
    global total
    for i in range(1000000):
        lock.acquire()
        total += 1
        lock.release()


def desc():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        total -= 1
        lock.release()

import threading
thread1 = threading.Thread(target=add)
thread2 = threading.Thread(target=desc)
thread1.start()
thread2.start()


#
thread1.join()
thread2.join()
print(total)

 

 

RLock

from threading import  RLock
#RLock在同一个线程里面,可以连续调用多次acquire, 一定要注意acquire的次数要和release的次数相等
total = 0
lock = RLock()
def add():
    #1. dosomething1
    #2. io操作
    # 1. dosomething3
    global lock
    global total
    for i in range(1000000):
        lock.acquire()
        lock.acquire()
        total += 1
        lock.release()
        lock.release()


def desc():
    global total
    global lock
    for i in range(1000000):
        lock.acquire()
        total -= 1
        lock.release()

import threading
thread1 = threading.Thread(target=add)
thread2 = threading.Thread(target=desc)
thread1.start()
thread2.start()


#
thread1.join()
thread2.join()
print(total)

 

python Lock、RLock

标签:注意   多次   release   color   lease   glob   star   desc   add   

原文地址:https://www.cnblogs.com/callyblog/p/11142218.html

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