python 多线程 锁lock/rlock(并行编程 4)

threading.Lock()
lock.acquire()
lock.release()

import threading

withlock=0
nolock=0
count=10000
lock=threading.Lock()

def inwithlock():
global withlock
for i in range(count):
lock.acquire()
withlock+=1
lock.release()
def dewithlock():
global withlock
for i in range(count):
lock.acquire()
withlock-=1
lock.release()
def innolock():
global nolock
for i in range(count):
nolock+=1
def denolock():
global nolock
for i in range(count):
nolock-=1

t1=threading.Thread(target=inwithlock)
t2=threading.Thread(target=dewithlock)
t3=threading.Thread(target=innolock)
t4=threading.Thread(target=denolock)
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
print("%s" % withlock)
print("%s" % nolock)

线程安全的操作

import threading

global var

count = 0
lock = threading.Lock()

Define a function for the thread

def print_time(threadName):
global count

c=0
with lock:
    while(c<100):
        c+=1
        count+=1
        print("{0}: set count to {1}".format( threadName, count) )

Create and run threads as follows

try:
threading.Thread( target=print_time, args=("Thread-1", ) ).start()
threading.Thread( target=print_time, args=("Thread-2", ) ).start()
threading.Thread( target=print_time, args=("Thread-3", ) ).start()
except Exception as e:
print("Error: unable to start thread")

RLOCK和LOCK的区别

1.2 死锁

Lock在下面的情形下会发生死锁

Lock.acquire()

Lock.acquire()

Lock.release()

Lock.release()

连续两次acquire请求,会导致死锁,因为第一次获得锁之后还没有释放,第二次再来申请,程序就阻塞在这里,导致第一次申请到的锁无法释放

1.3 可重入锁

RLock就不存在1.2中所提到的死锁

RLock.acquire()

RLock.acquire()

RLock.release()

RLock.release()

但是要保证,有多少次acquire就有多少次release

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 线程 操作系统线程理论 线程概念的引入背景 进程 之前我们已经了解了操作系统中进程的概念,程序并不能单独运行,只有...
    go以恒阅读 5,617评论 0 6
  • 线程状态新建,就绪,运行,阻塞,死亡。 线程同步多线程可以同时运行多个任务,线程需要共享数据的时候,可能出现数据不...
    KevinCool阅读 4,210评论 0 0
  • class threading.Thread(group=None,target=None,name=None,a...
    SkTj阅读 3,328评论 0 2
  • ### GIL global interpreter lock(cpython) 同一时刻只有一个线程运行在一个c...
    派派森森阅读 1,703评论 0 1
  • 环境 xubuntu anaconda pycharm python https://www.cnblogs.co...
    Ericoool阅读 5,910评论 0 0