举例讲解Python编程中对线程锁的使用


Posted in Python onJuly 12, 2016

python的内置数据结构比如列表和字典等是线程安全的,但是简单数据类型比如整数和浮点数则不是线程安全的,要这些简单数据类型的通过操作,就需要使用锁。

#!/usr/bin/env python3
# coding=utf-8

import threading

shared_resource_with_lock = 0
shared_resource_with_no_lock = 0
COUNT = 100000
shared_resource_lock = threading.Lock()

####LOCK MANAGEMENT##
def increment_with_lock():
  global shared_resource_with_lock
  for i in range(COUNT):
    shared_resource_lock.acquire()
    shared_resource_with_lock += 1
    shared_resource_lock.release()
    
def decrement_with_lock():
  global shared_resource_with_lock
  for i in range(COUNT):
    shared_resource_lock.acquire()
    shared_resource_with_lock -= 1
    shared_resource_lock.release()
    ####NO LOCK MANAGEMENT ##
  
def increment_without_lock():
  global shared_resource_with_no_lock
  for i in range(COUNT):
    shared_resource_with_no_lock += 1
  
def decrement_without_lock():
  global shared_resource_with_no_lock
  for i in range(COUNT):
    shared_resource_with_no_lock -= 1
  
####the Main program
if __name__ == "__main__":
  t1 = threading.Thread(target = increment_with_lock)
  t2 = threading.Thread(target = decrement_with_lock)
  t3 = threading.Thread(target = increment_without_lock)
  t4 = threading.Thread(target = decrement_without_lock)
  t1.start()
  t2.start()
  t3.start()
  t4.start()
  t1.join()
  t2.join()
  t3.join()
  t4.join()
  print ("the value of shared variable with lock management is %s"\
  %shared_resource_with_lock)
  print ("the value of shared variable with race condition is %s"\
  %shared_resource_with_no_lock)

执行结果:

$ ./threading_lock.py
the value of shared variable with lock management is 0
the value of shared variable with race condition is 0

又如:

import random
import threading
import time
logging.basicConfig(level=logging.DEBUG,
          format='(%(threadName)-10s) %(message)s',
          )
          
class Counter(object):
  def __init__(self, start=0):
    self.lock = threading.Lock()
    self.value = start
  def increment(self):
    logging.debug(time.ctime(time.time()))
    logging.debug('Waiting for lock')
    self.lock.acquire()
    try:
      pause = random.randint(1,3)
      logging.debug(time.ctime(time.time()))
      logging.debug('Acquired lock')      
      self.value = self.value + 1
      logging.debug('lock {0} seconds'.format(pause))
      time.sleep(pause)
    finally:
      self.lock.release()
def worker(c):
  for i in range(2):
    pause = random.randint(1,3)
    logging.debug(time.ctime(time.time()))
    logging.debug('Sleeping %0.02f', pause)
    time.sleep(pause)
    c.increment()
  logging.debug('Done')
counter = Counter()
for i in range(2):
  t = threading.Thread(target=worker, args=(counter,))
  t.start()
logging.debug('Waiting for worker threads')
main_thread = threading.currentThread()
for t in threading.enumerate():
  if t is not main_thread:
    t.join()
logging.debug('Counter: %d', counter.value)

执行结果:

$ python threading_lock.py
(Thread-1 ) Tue Sep 15 15:49:18 2015
(Thread-1 ) Sleeping 3.00
(Thread-2 ) Tue Sep 15 15:49:18 2015
(MainThread) Waiting for worker threads
(Thread-2 ) Sleeping 2.00
(Thread-2 ) Tue Sep 15 15:49:20 2015
(Thread-2 ) Waiting for lock
(Thread-2 ) Tue Sep 15 15:49:20 2015
(Thread-2 ) Acquired lock
(Thread-2 ) lock 2 seconds
(Thread-1 ) Tue Sep 15 15:49:21 2015
(Thread-1 ) Waiting for lock
(Thread-2 ) Tue Sep 15 15:49:22 2015
(Thread-1 ) Tue Sep 15 15:49:22 2015
(Thread-2 ) Sleeping 2.00
(Thread-1 ) Acquired lock
(Thread-1 ) lock 1 seconds
(Thread-1 ) Tue Sep 15 15:49:23 2015
(Thread-1 ) Sleeping 2.00
(Thread-2 ) Tue Sep 15 15:49:24 2015
(Thread-2 ) Waiting for lock
(Thread-2 ) Tue Sep 15 15:49:24 2015
(Thread-2 ) Acquired lock
(Thread-2 ) lock 1 seconds
(Thread-1 ) Tue Sep 15 15:49:25 2015
(Thread-1 ) Waiting for lock
(Thread-1 ) Tue Sep 15 15:49:25 2015
(Thread-1 ) Acquired lock
(Thread-1 ) lock 2 seconds
(Thread-2 ) Done
(Thread-1 ) Done
(MainThread) Counter: 4

acquire()中传入False值,可以检查是否获得了锁。比如:

import logging
import threading
import time
logging.basicConfig(level=logging.DEBUG,
          format='(%(threadName)-10s) %(message)s',
          )
          
def lock_holder(lock):
  logging.debug('Starting')
  while True:
    lock.acquire()
    try:
      logging.debug('Holding')
      time.sleep(0.5)
    finally:
      logging.debug('Not holding')
      lock.release()
    time.sleep(0.5)
  return
          
def worker(lock):
  logging.debug('Starting')
  num_tries = 0
  num_acquires = 0
  while num_acquires < 3:
    time.sleep(0.5)
    logging.debug('Trying to acquire')
    have_it = lock.acquire(0)
    try:
      num_tries += 1
      if have_it:
        logging.debug('Iteration %d: Acquired',
               num_tries)
        num_acquires += 1
      else:
        logging.debug('Iteration %d: Not acquired',
               num_tries)
    finally:
      if have_it:
        lock.release()
  logging.debug('Done after %d iterations', num_tries)
lock = threading.Lock()
holder = threading.Thread(target=lock_holder,
             args=(lock,),
             name='LockHolder')
holder.setDaemon(True)
holder.start()
worker = threading.Thread(target=worker,
             args=(lock,),
             name='Worker')
worker.start()

执行结果:

$ python threading_lock_noblock.py
(LockHolder) Starting
(LockHolder) Holding
(Worker  ) Starting
(LockHolder) Not holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 1: Acquired
(LockHolder) Holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 2: Not acquired
(LockHolder) Not holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 3: Acquired
(LockHolder) Holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 4: Not acquired
(LockHolder) Not holding
(Worker  ) Trying to acquire
(Worker  ) Iteration 5: Acquired
(Worker  ) Done after 5 iterations

线程安全锁

threading.RLock()

返回可重入锁对象。重入锁必须由获得它的线程释放。一旦线程获得了重入锁,同一线程可不阻塞地再次获得,获取之后必须释放。

通常一个线程只能获取一次锁:

import threading

lock = threading.Lock()

print 'First try :', lock.acquire()
print 'Second try:', lock.acquire(0)

执行结果:

$ python threading_lock_reacquire.py
First try : True
Second try: False

使用RLock可以获取多次锁:

import threading
lock = threading.RLock()
print 'First try :', lock.acquire()
print 'Second try:', lock.acquire(0)

执行结果:

python threading_rlock.py
First try : True
Second try: 1

再来看一个例子:

#!/usr/bin/env python3
# coding=utf-8
import threading
import time
class Box(object):
  lock = threading.RLock()
  def __init__(self):
    self.total_items = 0
  def execute(self,n):
    Box.lock.acquire()
    self.total_items += n
    Box.lock.release()
  def add(self):
    Box.lock.acquire()
    self.execute(1)
    Box.lock.release()
  def remove(self):
    Box.lock.acquire()
    self.execute(-1)
    Box.lock.release()
    
## These two functions run n in separate
## threads and call the Box's methods    
def adder(box,items):
  while items > 0:
    print ("adding 1 item in the box\n")
    box.add()
    time.sleep(5)
    items -= 1
    
def remover(box,items):
  while items > 0:
    print ("removing 1 item in the box")
    box.remove()
    time.sleep(5)
    items -= 1
    
## the main program build some
## threads and make sure it works
if __name__ == "__main__":
  items = 5
  print ("putting %s items in the box " % items)
  box = Box()
  t1 = threading.Thread(target=adder,args=(box,items))
  t2 = threading.Thread(target=remover,args=(box,items))
  t1.start()
  t2.start()
  t1.join()
  t2.join()
  print ("%s items still remain in the box " % box.total_items)

执行结果:

$ python3 threading_rlock2.py
putting 5 items in the box 
adding 1 item in the box
removing 1 item in the box
adding 1 item in the box
removing 1 item in the box
adding 1 item in the box
removing 1 item in the box
removing 1 item in the box
adding 1 item in the box
removing 1 item in the box
adding 1 item in the box
0 items still remain in the box
Python 相关文章推荐
Python socket.error: [Errno 98] Address already in use的原因和解决方法
Aug 25 Python
简单了解OpenCV是个什么东西
Nov 10 Python
用pyqt5 给按钮设置图标和css样式的方法
Jun 24 Python
numpy和pandas中数组的合并、拉直和重塑实例
Jun 28 Python
把django中admin后台界面的英文修改为中文显示的方法
Jul 26 Python
处理Selenium3+python3定位鼠标悬停才显示的元素
Jul 31 Python
Python操作SQLite/MySQL/LMDB数据库的方法
Nov 07 Python
Python实现新型冠状病毒传播模型及预测代码实例
Feb 05 Python
Windows下Anaconda和PyCharm的安装与使用详解
Apr 23 Python
python使用Word2Vec进行情感分析解析
Jul 31 Python
通俗易懂了解Python装饰器原理
Sep 17 Python
selenium与xpath之获取指定位置的元素的实现
Jan 26 Python
使用Python编写一个最基础的代码解释器的要点解析
Jul 12 #Python
Python中使用bidict模块双向字典结构的奇技淫巧
Jul 12 #Python
Python使用SocketServer模块编写基本服务器程序的教程
Jul 12 #Python
使用Python的Flask框架表单插件Flask-WTF实现Web登录验证
Jul 12 #Python
Python的Flask框架标配模板引擎Jinja2的使用教程
Jul 12 #Python
深度定制Python的Flask框架开发环境的一些技巧总结
Jul 12 #Python
Python的面向对象编程方式学习笔记
Jul 12 #Python
You might like
删除无限分类并同时删除它下面的所有子分类的方法
2010/08/08 PHP
PHP使用socket发送HTTP请求的方法
2016/02/14 PHP
PHP快速排序quicksort实例详解
2016/09/28 PHP
laravel5.2实现区分前后台用户登录的方法
2017/01/11 PHP
laravel中命名路由的使用方法
2017/02/24 PHP
PHP优化之批量操作MySQL实例分析
2020/04/23 PHP
Javascript常考语句107条收集
2010/03/09 Javascript
JQuery UI的拖拽功能实现方法小结
2012/03/14 Javascript
jquery实现可拖动DIV自定义保存到数据的实例
2013/11/20 Javascript
javascript特殊用法示例介绍
2013/11/29 Javascript
兼容Firefox的Javascript XSLT 处理XML文件
2014/12/31 Javascript
jQuery中常用的遍历函数用法实例总结
2015/09/01 Javascript
jQuery之动画效果大全
2016/11/09 Javascript
用headjs来管理和加载js 提高网站加载速度
2016/11/29 Javascript
基于jQuery实现顶部导航栏功能
2016/12/27 Javascript
JQuery获取鼠标进入和离开容器的方向
2016/12/29 Javascript
用nodeJS搭建本地文件服务器的几种方法小结
2017/03/16 NodeJs
Vuex之理解Mutations的用法实例
2017/04/19 Javascript
Vue中使用vux的配置详解
2017/05/05 Javascript
vue2.0 如何把子组件的数据传给父组件(推荐)
2018/01/15 Javascript
JS实现为动态创建的元素添加事件操作示例
2018/03/17 Javascript
详解Vue.directive 自定义指令
2019/03/27 Javascript
vue搜索和vue模糊搜索代码实例
2019/05/07 Javascript
js实现橱窗展示效果
2020/01/11 Javascript
[53:52]EG vs VGJ.T 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
基于Django静态资源部署404的解决方法
2019/07/28 Python
python 多进程队列数据处理详解
2019/12/23 Python
python实现TCP文件传输
2020/03/20 Python
澳大利亚排名第一的狂热牛仔品牌:ONETEASPOON
2018/11/20 全球购物
美国家居装饰店:Pier 1
2019/09/04 全球购物
岗位职责的定义
2013/11/10 职场文书
甘南现象心得体会
2014/09/11 职场文书
2014县政府领导班子三严三实对照检查材料思想汇报
2014/09/26 职场文书
2014年学习部工作总结
2014/11/12 职场文书
优秀英文求职信范文
2015/03/19 职场文书
城镇居民医疗保险工作总结
2015/08/10 职场文书