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类的继承和多态代码详解
Dec 27 Python
Python中判断输入是否为数字的实现代码
May 26 Python
python如何查看微信消息撤回
Nov 27 Python
python根据txt文本批量创建文件夹
Dec 08 Python
python使用wxpy实现微信消息防撤回脚本
Apr 29 Python
python遍历文件目录、批量处理同类文件
Aug 31 Python
django drf框架自带的路由及最简化的视图
Sep 10 Python
python 在threading中如何处理主进程和子线程的关系
Apr 25 Python
在pycharm中使用matplotlib.pyplot 绘图时报错的解决
Jun 01 Python
Python脚本如何在bilibili中查找弹幕发送者
Jun 04 Python
Python实现迪杰斯特拉算法过程解析
Sep 18 Python
matplotlib绘制多子图共享鼠标光标的方法示例
Jan 08 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 is_file 判断给定文件名是否为一个正常的文件
2010/05/10 PHP
PHP队列用法实例
2014/11/05 PHP
php绘图之在图片上写中文和英文的方法
2015/01/24 PHP
浅析THINKPHP的addAll支持的最大数据量
2015/02/03 PHP
详解PHP+AJAX无刷新分页实现方法
2015/11/03 PHP
php编程实现简单的网页版计算器功能示例
2017/04/26 PHP
在Linux上用forever实现Node.js项目自启动
2014/07/09 Javascript
node.js中的querystring.parse方法使用说明
2014/12/10 Javascript
jQuery实用技巧必备(下)
2015/11/03 Javascript
jqGrid表格应用之新增与删除数据附源码下载
2015/12/02 Javascript
深入理解$.each和$(selector).each
2016/05/15 Javascript
简单封装js的dom查询实例代码
2016/07/08 Javascript
jquery validate表单验证插件
2016/09/06 Javascript
教你用十行node.js代码读取docx的文本
2017/03/08 Javascript
angular异步验证防抖踩坑实录
2019/12/01 Javascript
Vue SSR 即时编译技术的实现
2020/05/06 Javascript
详解小程序横屏方案对比
2020/06/28 Javascript
跟老齐学Python之类的细节
2014/10/13 Python
python中查看变量内存地址的方法
2015/05/05 Python
Python打包文件夹的方法小结(zip,tar,tar.gz等)
2016/09/18 Python
Python元字符的用法实例解析
2018/01/17 Python
python 限制函数调用次数的实例讲解
2018/04/21 Python
python构建指数平滑预测模型示例
2019/11/21 Python
tensorflow 变长序列存储实例
2020/01/20 Python
CSS3教程(10):CSS3 HSL声明设置颜色
2009/04/02 HTML / CSS
Hertz荷兰:荷兰和全球租车
2018/01/07 全球购物
Nike俄罗斯官方网站:Nike RU
2021/03/05 全球购物
德国BA保镖药房中文网:Bodyguard Apotheke
2021/03/09 全球购物
会计自荐书
2013/12/02 职场文书
优秀社区干部事迹材料
2014/02/03 职场文书
开业庆典主持词
2014/03/21 职场文书
高考标语大全
2014/06/05 职场文书
三方股东合作协议书范本
2014/09/28 职场文书
夫妻分居协议书范本
2014/11/28 职场文书
pyqt5蒙版遮罩mask,setmask的使用
2021/06/11 Python
win10蓝屏0xc0000001安全模式进不了怎么办?win10出现0xc0000001的解决方法
2022/08/05 数码科技