Python线程同步的实现代码
作者:Harvard_Fly 发布时间:2022-10-01 00:20:48
本文介绍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()
来源:http://www.cnblogs.com/FG123/p/9704158.html
猜你喜欢
- 概述在使用keras中的keras.backend.batch_dot和tf.matmul实现功能其实是一样的智能矩阵乘法,比如A,B,C,
- 本文实例为大家分享了opencv实现答题卡识别的具体代码,供大家参考,具体内容如下"""识别答题卡"
- mat矩阵和npy矩阵互相转换numpy.narray矩阵保存为mat文件import numpy as npimport scipy.io
- 最近在工作中遇到一个问题,就是有一个功能希望在各种服务器上实现,而服务器上的系统版本可能都不一样,有的是 CentOS 6.x,有的是 Ce
- <SCRIPT language="JavaScript"><!-- Beginfunction mo
- 如果能,请问如何实现 谢谢set aa=server.cre
- 2009年 6月6日,空间4岁啦!与此同时Qzone月登录用户2亿,同时在线用户也突破了1000万。这是让人欢欣雀跃的数字,在空间同事眼里,
- 使用 str.split() 方法将字符串转换为数组,例如 array = string.split(',')。 str.s
- KNN核心算法函数,具体内容如下#! /usr/bin/env python3# -*- coding: utf-8 -*-# fileNa
- 目录01 all or any02 dir03 列表(list)推导式04 pprint05 repr06 sh07 Type hints0
- 有关pygal的介绍和安装,大家可以参阅《pip和pygal的安装实例教程》,然后利用pygal实现画世界地图。代码如下:#coding=u
- 如下所示:#-*- encoding:utf-8 -*-import csvimport sys,osimport pymysql def
- 1、800*600下,网页宽度保持在778以内,就不会出现水平滚动条,高度则视版面和内容决定。2、1024*768下,网页宽度保持在1002
- 本文实例讲述了Python实现的递归神经网络。分享给大家供大家参考,具体如下:# Recurrent Neural Networksimpo
- 两年前发表的《The visual design of Web 2.0》中提到“Rounded everything”,圆角因使人感觉舒适的
- 前言提起selenium想必大家都不陌生,作为一款知名的Web自动化测试框架,selenium支持多款主流浏览器,提供了功能丰富的API接口
- 安装SQL Server 遇到错误提示:以前的某个程序安装已在安装计算机上创建挂起的文件操作。运行安装程序之前必须重新启动计算机!。找了半天
- 本篇博文主要介绍在Python3中如何构造含参构造函数样例如下:class MyOdlHttp: username = '
- 在jupyter notebook或者是 Qtconsole下编译运行一个简单的pyqt程序,总是报错:The kernel appears
- 1. 安装yaml库想要使用python实现yaml与json格式互相转换,需要先下载pip,再通过pip安装yaml库。如何下载以及使用p