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进行基础的函数式编程的教程
Mar 31 Python
Python全局变量用法实例分析
Jul 19 Python
python下os模块强大的重命名方法renames详解
Mar 07 Python
Django + Uwsgi + Nginx 实现生产环境部署的方法
Jun 20 Python
python中的tcp示例详解
Dec 09 Python
python实现布隆过滤器及原理解析
Dec 08 Python
Django Admin设置应用程序及模型顺序方法详解
Apr 01 Python
QML实现钟表效果
Jun 02 Python
Django Session和Cookie分别实现记住用户登录状态操作
Jul 02 Python
python logging模块的使用
Sep 07 Python
Django配置Bootstrap, js实现过程详解
Oct 13 Python
python数据库批量插入数据的实现(executemany的使用)
Apr 30 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+Ajax检测用户名或邮件注册时是否已经存在实例教程
2014/08/23 PHP
抛弃 PHP 代价太高
2016/04/26 PHP
JQuery 前台切换网站的样式实现
2009/06/22 Javascript
JavaScrip单线程引擎工作原理分析
2010/09/04 Javascript
jquery调用wcf并展示出数据的方法
2011/07/07 Javascript
JavaScript 上万关键字瞬间匹配实现代码
2013/07/07 Javascript
介绍一个简单的JavaScript类框架
2015/06/24 Javascript
JQ技术实现注册页面带有校验密码强度
2015/07/27 Javascript
jquery仿百度百科底部浮动导航特效
2015/08/08 Javascript
jQuery实现购物车表单自动结算效果实例
2015/08/10 Javascript
js实现iframe框架取值的方法(兼容IE,firefox,chrome等)
2015/11/26 Javascript
jquery插件uploadify实现带进度条的文件批量上传
2015/12/13 Javascript
Nodejs爬虫进阶教程之异步并发控制
2016/02/15 NodeJs
jQuery实现拼图小游戏(实例讲解)
2017/07/24 jQuery
zTree获取当前节点的下一级子节点数实例
2017/09/05 Javascript
Js中使用正则表达式验证输入是否有特殊字符
2018/09/07 Javascript
基于Fixed定位的框选功能的实现代码
2019/05/13 Javascript
vue父子模板传值问题解决方法案例分析
2020/02/26 Javascript
WebStorm中如何将自己的代码上传到github示例详解
2020/10/28 Javascript
[00:09]DOTA2全国高校联赛 精彩活动引爆全场
2018/05/30 DOTA
Python中字符串对齐方法介绍
2015/05/21 Python
Python网络编程中urllib2模块的用法总结
2016/07/12 Python
python 3.5下xadmin的使用及修复源码bug
2017/05/10 Python
python实现简单tftp(基于udp协议)
2018/07/30 Python
Python 实现取矩阵的部分列,保存为一个新的矩阵方法
2018/11/14 Python
Python下利用BeautifulSoup解析HTML的实现
2020/01/17 Python
python3发送request请求及查看返回结果实例
2020/04/30 Python
H5混合开发app如何升级的方法
2018/01/10 HTML / CSS
美国高级音响品牌:Master&Dynamic
2018/07/05 全球购物
linux面试题参考答案(10)
2013/11/04 面试题
晚会邀请函范文
2014/01/24 职场文书
个人四风问题原因分析及整改措施
2014/09/28 职场文书
教你怎么用python实现字符串转日期
2021/05/24 Python
vue实现水波涟漪效果的点击反馈指令
2021/05/31 Vue.js
小程序实现悬浮按钮的全过程记录
2021/10/16 HTML / CSS
MySQL GTID复制的具体使用
2022/05/20 MySQL