Python线程同步的实现代码


Posted in Python onOctober 03, 2018

本文介绍Python中的线程同步对象,主要涉及 thread 和 threading 模块。

threading 模块提供的线程同步原语包括:Lock、RLock、Condition、Event、Semaphore等对象。

线程执行

join与setDaemon

子线程在主线程运行结束后,会继续执行完,如果给子线程设置为守护线程(setDaemon=True),主线程运行结束子线程即结束;

如果join()线程,那么主线程会等待子线程执行完再执行。

import threading
import time


def get_thread_a():
 print("get thread A started")
 time.sleep(3)
 print("get thread A end")


def get_thread_b():
 print("get thread B started")
 time.sleep(5)
 print("get thread B end")


if __name__ == "__main__":
 thread_a = threading.Thread(target=get_thread_a)
 thread_b = threading.Thread(target=get_thread_b)
 start_time = time.time()
 thread_b.setDaemon(True)
 thread_a.start()
 thread_b.start()
 thread_a.join()
 
 end_time = time.time()
 print("execution time: {}".format(end_time - start_time))

thread_a是join,首先子线程thread_a执行,thread_b是守护线程,当主线程执行完后,thread_b不会再执行执行结果如下:

get thread A started
get thread B started
get thread A end
execution time: 3.003199815750122

线程同步

当线程间共享全局变量,多个线程对该变量执行不同的操作时,该变量最终的结果可能是不确定的(每次线程执行后的结果不同),如:对count变量执行加减操作 ,count的值是不确定的,要想count的值是一个确定的需对线程执行的代码段加锁。

python对线程加锁主要有Lock和Rlock模块

Lock: 

from threading import Lock
lock = Lock()
lock.acquire()
lock.release()

Lock有acquire()和release()方法,这两个方法必须是成对出现的,acquire()后面必须release()后才能再acquire(),否则会造成死锁

Rlock:

鉴于Lock可能会造成死锁的情况,RLock(可重入锁)对Lock进行了改进,RLock可以在同一个线程里面连续调用多次acquire(),但必须再执行相同次数的release()

from threading import RLock
lock = RLock()
lock.acquire()
lock.acquire()
lock.release()
lock.release()

condition(条件变量),线程在执行时,当满足了特定的条件后,才可以访问相关的数据

import threading

def get_thread_a(condition):
 with condition:
  condition.wait()
  print("A : Hello B,that's ok")
  condition.notify()
  condition.wait()
  print("A : I'm fine,and you?")
  condition.notify()
  condition.wait()
  print("A : Nice to meet you")
  condition.notify()
  condition.wait()
  print("A : That's all for today")
  condition.notify()

def get_thread_b(condition):
 with condition:
  print("B : Hi A, Let's start the conversation")
  condition.notify()
  condition.wait()
  print("B : How are you")
  condition.notify()
  condition.wait()
  print("B : I'm fine too")
  condition.notify()
  condition.wait()
  print("B : Nice to meet you,too")
  condition.notify()
  condition.wait()
  print("B : Oh,goodbye")

if __name__ == "__main__":
 condition = threading.Condition()
 thread_a = threading.Thread(target=get_thread_a, args=(condition,))
 thread_b = threading.Thread(target=get_thread_b, args=(condition,))
 thread_a.start()
 thread_b.start()

Condition内部有一把锁,默认是RLock,在调用wait()和notify()之前必须先调用acquire()获取这个锁,才能继续执行;当wait()和notify()执行完后,需调用release()释放这个锁,在执行with condition时,会先执行acquire(),with结束时,执行了release();所以condition有两层锁,最底层锁在调用wait()时会释放,同时会加一把锁到等待队列,等待notify()唤醒释放锁

wait() :允许等待某个条件变量的通知,notify()可唤醒

notify(): 唤醒等待队列wait()

执行结果:

B : Hi A, Let's start the conversation
A : Hello B,that's ok
B : How are you
A : I'm fine,and you?
B : I'm fine too
A : Nice to meet you
B : Nice to meet you,too
A : That's all for today
B : Oh,goodbye

Semaphore(信号量)

用于控制线程的并发数,如爬虫中请求次数过于频繁会被禁止ip,每次控制爬取网页的线程数量可在一定程度上防止ip被禁;文件读写中,控制写线程每次只有一个,读线程可多个。

import time
import threading


def get_thread_a(semaphore,i):
 time.sleep(1)
 print("get thread : {}".format(i))
 semaphore.release()


def get_thread_b(semaphore):
 for i in range(10):
  semaphore.acquire()
  thread_a = threading.Thread(target=get_thread_a, args=(semaphore,i))
  thread_a.start()


if __name__ == "__main__":
 semaphore = threading.Semaphore(2)
 thread_b = threading.Thread(target=get_thread_b, args=(semaphore,))
 thread_b.start()

上述示例了每隔1秒并发两个线程执行的情况,当调用一次semaphore.acquire()时,Semaphore的数量就减1,直至Semaphore数量为0时被锁上,当release()后Semaphore数量加1。Semaphore在本质上是调用的Condition,semaphore.acquire()在Semaphore的值为0的条件下会调用Condition.wait(), 否则将值减1,semaphore.release()会将Semaphore的值加1,并调用Condition.notify()

Semaphore源码

def acquire(self, blocking=True, timeout=None):
  if not blocking and timeout is not None:
   raise ValueError("can't specify timeout for non-blocking acquire")
  rc = False
  endtime = None
  with self._cond:
   while self._value == 0:
    if not blocking:
     break
    if timeout is not None:
     if endtime is None:
      endtime = _time() + timeout
     else:
      timeout = endtime - _time()
      if timeout <= 0:
       break
    self._cond.wait(timeout)
   else:
    self._value -= 1
    rc = True
  return rc

def release(self):
  with self._cond:
   self._value += 1
   self._cond.notify()

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Python 相关文章推荐
python结合API实现即时天气信息
Jan 19 Python
Python 使用requests模块发送GET和POST请求的实现代码
Sep 21 Python
python+pillow绘制矩阵盖尔圆简单实例
Jan 16 Python
python和shell获取文本内容的方法
Jun 05 Python
python3实现磁盘空间监控
Jun 21 Python
python使用tcp实现局域网内文件传输
Mar 20 Python
Python实现爬取亚马逊数据并打印出Excel文件操作示例
May 16 Python
python输出决策树图形的例子
Aug 09 Python
Python测试线程应用程序过程解析
Dec 31 Python
Python面向对象编程基础实例分析
Jan 17 Python
Pycharm激活码激活两种快速方式(附最新激活码和插件)
Mar 12 Python
python实现吃苹果小游戏
Mar 21 Python
详解通过API管理或定制开发ECS实例
Sep 30 #Python
Python 使用类写装饰器的小技巧
Sep 30 #Python
浅谈django三种缓存模式的使用及注意点
Sep 30 #Python
使用Python实现租车计费系统的两种方法
Sep 29 #Python
Python实现App自动签到领取积分功能
Sep 29 #Python
10个Python小技巧你值得拥有
Sep 29 #Python
实例分析python3实现并发访问水平切分表
Sep 29 #Python
You might like
需要使用php模板的朋友必看的很多个顶级PHP模板引擎比较分析
2008/05/26 PHP
PHP查找数值数组中不重复最大和最小的10个数的方法
2015/04/20 PHP
PHP的Socket通信之UDP通信实例
2015/07/02 PHP
使用PHP免费发送定时短信的实例
2016/10/24 PHP
THINKPHP3.2使用soap连接webservice的解决方法
2017/12/13 PHP
PHP判断访客是否手机端(移动端浏览器)访问的方法总结【4种方法】
2019/03/27 PHP
jquery表单验证使用插件formValidator
2012/11/10 Javascript
js实现div闪烁原理及实现代码
2014/06/24 Javascript
jQuery图片特效插件Revealing实现拉伸放大
2015/04/22 Javascript
AngularJs学习第八篇 过滤器filter创建
2016/06/08 Javascript
使用store来优化React组件的方法
2017/10/23 Javascript
Vue.js在数组中插入重复数据的实现代码
2017/11/17 Javascript
vue侧边栏动态生成下级菜单的方法
2018/09/07 Javascript
微信小程序功能之全屏滚动效果的实现代码
2018/11/22 Javascript
微信小程序class封装http代码实例
2019/08/24 Javascript
Python时区设置方法与pytz查询时区教程
2013/11/27 Python
使用cx_freeze把python打包exe示例
2014/01/24 Python
python根据出生日期获得年龄的方法
2015/03/31 Python
python结合API实现即时天气信息
2016/01/19 Python
Python使用cookielib模块操作cookie的实例教程
2016/07/12 Python
Python基础教程之tcp socket编程详解及简单实例
2017/02/23 Python
Python实现KNN邻近算法
2021/01/28 Python
使用Python制作自动推送微信消息提醒的备忘录功能
2018/09/06 Python
带你认识Django
2019/01/15 Python
Pytest框架之fixture的详细使用教程
2020/04/07 Python
用CSS3绘制三角形的简单方法
2015/07/17 HTML / CSS
HTML5标签与HTML4标签的区别示例介绍
2013/07/18 HTML / CSS
HTML5 Canvas的常用线条属性值总结
2016/03/17 HTML / CSS
荷兰浴室和卫浴网上商店:Badkamerxxl.nl
2020/10/06 全球购物
Shell编程面试题
2016/05/29 面试题
房地产财务管理制度
2014/02/02 职场文书
给学校的建议书
2014/03/12 职场文书
诉讼财产保全担保书
2014/05/20 职场文书
ktv好的活动方案
2014/08/15 职场文书
大学生活委员竞选稿
2015/11/21 职场文书
pytorch 实现变分自动编码器的操作
2021/05/24 Python