前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 多线程 锁lock/rlock(并行编程 4)

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

作者头像
用户5760343
发布2019-07-30 10:57:50
4930
发布2019-07-30 10:57:50
举报
文章被收录于专栏:sktj

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

代码语言:javascript
复制
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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.07.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 线程安全的操作
  • global var
  • Define a function for the thread
  • Create and run threads as follows
  • RLOCK和LOCK的区别
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档