林州网站建设哪家专业六安建设局网站
- 作者: 五速梦信息网
- 时间: 2026年03月21日 10:30
当前位置: 首页 > news >正文
林州网站建设哪家专业,六安建设局网站,济南网站建设建站,潍坊网站建设求职简历Python | threading
简介 Python的threading模块是用于创建和管理线程的标准库。线程是在同一进程中执行的多个执行路径#xff0c;使程序可以同时执行多个任务。 threading模块提供了Thread类#xff0c;通过创建Thread对象#xff0c;可以轻松地在Python中启动和管理…Python | threading
简介 Python的threading模块是用于创建和管理线程的标准库。线程是在同一进程中执行的多个执行路径使程序可以同时执行多个任务。 threading模块提供了Thread类通过创建Thread对象可以轻松地在Python中启动和管理线程。
多线程 2.1. 继承方式 import threading import timeclass MyThread(threading.Thread):def run(self):print(start working)time.sleep(1)print(end work)my_thread MyThread() my_thread.start() my_thread.join()2.2. 回调方式 import threading import timedef run():print(start working)time.sleep(1)print(end work)my_thread threading.Thread(targetrun) my_thread.start() my_thread.join()3. threading.Lock 锁 import threadingclass Fruits:list: [str] []lock: threading.Lock threading.Lock()def add(self, fruit: str):with self.lock:index self.get_index(fruit)if index -1:# 存在更新self.list.append(fruit)def update(self, old: str, new: str):with self.lock:index self.get_index(old)if index ! -1:# 存在更新self.list[index] newdef get_index(self, fruit: str) - int:with self.lock:return self.__get_index(fruit)def __get_index(self, fruit: str) - int:for index in range(len(self.list)):if self.list[index] fruit:return indexreturn -1fruits Fruits() fruits.add(Banana) fruits.update(Banana, Apple) print(fruits.get_index(Banana)) print(fruits.get_index(Apple))4. threading.RLock 重入锁 此处RLock并非读写锁表示重入锁同一个线程可以多次获取锁。 对比Lock的示例代码RLock经常使用在一个API既需要内部使用又需要开放外部访问保证线程安全时特别有用。 import threadingclass Fruits:list: [str] []lock: threading.RLock threading.RLock()def add(self, fruit: str):with self.lock:index self.get_index(fruit)if index -1:# 存在更新self.list.append(fruit)def update(self, old: str, new: str):with self.lock:index self.get_index(old)if index ! -1:# 存在更新self.list[index] newdef get_index(self, fruit: str) - int:with self.lock:for index in range(len(self.list)):if self.list[index] fruit:return indexreturn -1fruits Fruits() fruits.add(Banana) fruits.update(Banana, Apple) print(fruits.get_index(Banana)) print(fruits.get_index(Apple))5. threading.Timer 非周期性定时器 import threading import datetimedef work():print(fhello {datetime.datetime.now()})timer threading.Timer(2, work)
2秒过后调用work
timer.start()
timer.cancel()6. threading.Semaphore 信号量
常用方法 semaphore threading.Semaphore(value2) # 总资源数量2 semaphore.acquire() # 请求资源 semaphore.release(n1) # 释放资源使用示例中间件 import threading# 令牌桶网站同时只允许1000人访问 tokenBucket threading.Semaphore(value1000)class HTTPRequest:passdef abort(req: HTTPRequest):passdef next_step(req: HTTPRequest):pass# 模拟HTTP中间件 def middleware(req: HTTPRequest):b: bool Falsetry:# 获取令牌b tokenBucket.acquire(blockingFalse)if not b:# 失败中止访问abort(req)# 成功继续下一步next_step(req)finally:if b:# 归还令牌tokenBucket.release()7. threading.BoundedSemaphore 边界信号量 与threading.Semaphore不同的是资源数量被限制不能超过初始资源数量。 import threadingsemaphore threading.BoundedSemaphore(value10) semaphore.acquire() semaphore.release()
Exception: Semaphore released too many times
semaphore.release()8. threading.Barrier 栅栏 threading.Barrier 是 Python 中 threading 模块中的同步原语它用于在多个线程中进行同步确保这些线程在达到指定的屏障点之前都会被阻塞然后在所有线程都到达屏障点后同时继续执行。 threading.Barrier 适用于需要所有线程到达某个点之后再继续执行的场景比如等待所有线程完成一定阶段的工作后再进行下一阶段的操作。 threading.Barrier 的常用方法是 init(parties, actionNone): 创建一个 Barrier 对象。parties 参数指定需要等待的线程数量当有 parties 个线程都调用 wait() 方法后所有线程将同时释放并继续执行。可选的 action 参数可以指定一个回调函数当所有线程释放后此回调函数将在释放线程中的一个线程中执行。wait(timeoutNone): 阻塞线程直到所有参与线程都调用了 wait() 方法并达到屏障点。可选的 timeout 参数用于设置等待的超时时间如果超过此时间线程将被解除阻塞。 下面是 threading.Barrier 的一个简单示例 import threadingdef worker(barrier, name):print(f{name}: 执行任务前)barrier.wait()print(f{name}: 执行任务后)# 创建 Barrier 对象需要等待3个线程 barrier threading.Barrier(3)# 创建3个工作线程 thread1 threading.Thread(targetworker, args(barrier, 线程1)) thread2 threading.Thread(targetworker, args(barrier, 线程2)) thread3 threading.Thread(targetworker, args(barrier, 线程3))# 启动工作线程 thread1.start() thread2.start() thread3.start()# 等待所有线程完成 thread1.join() thread2.join() thread3.join()print(所有线程已完成。)9. threading.Event 事件 threading.Event 是 Python 中 threading 模块中的同步原语它允许线程等待直到被其他线程设置为真的事件。它通常用于协调多个线程的活动并促进它们之间的通信。 threading.Event 的主要作用是为线程提供一个简单的机制使它们能够在特定条件满足之前暂停执行。与 threading.Event 相关的两个主要方法是 set(): 设置事件为真。正在使用 wait() 方法等待事件的线程将被释放可以继续执行。 clear(): 重置事件为假。随后调用 wait() 的线程将被阻塞直到再次使用 set() 方法设置事件。
除了这两个方法之外还有 wait(timeoutNone) 方法。当线程调用 wait() 时它将被阻塞直到事件被设置或达到可选的 timeout 参数为止。如果提供了超时并且事件在指定的时间内没有被设置线程将继续执行而不考虑事件状态。 下面是 threading.Event 的一个基本示例 import random import threading import timeevent threading.Event() runners [runner1, runner2, runner3] threads []def start(name: str):print(f{name} 准备就绪)event.wait()print(f{name} 起跑)time.sleep(random.randint(1, 3))print(f{name} 到达终点)# 准备 for runner in runners:t threading.Thread(targetstart, args(runner,))t.start()threads.append(t)# 让所有跑步者都进入等待此处处理并不优雅但这里主要目的是为了演示event。 time.sleep(1)发令
event.set()for t in threads:t.join()
threading.Condition threading.Condition 是 Python 中 threading 模块中的同步原语它用于在多个线程之间进行复杂的协调和通信。它提供了一个通用的条件变量允许线程等待某个条件为真或者在满足条件时通知其他等待的线程。 threading.Condition 主要用途是在多线程环境下实现线程间的协作特别是用于生产者-消费者模式和线程间的消息传递。通过使用 threading.Condition我们可以让一个线程等待直到满足特定条件然后另一个线程通知条件已经满足从而实现线程间的同步。 threading.Condition 的常用方法有 init(lockNone): 创建一个 Condition 对象。可选的 lock 参数指定一个锁对象用于在内部同步条件的访问。如果不提供锁对象Condition 会自动创建一个默认的锁对象。acquire(): 获取底层关联的锁用于保护共享资源或条件。release(): 释放底层关联的锁。wait(timeoutNone): 等待条件为真。调用此方法将释放关联的锁并阻塞线程直到另一个线程调用 notify() 或 notify_all() 方法通知条件为真或超时。notify(n1): 唤醒等待此条件的一个线程。默认情况下唤醒一个等待的线程如果指定 n 参数将唤醒 n 个等待的线程。notify_all(): 唤醒所有等待此条件的线程。 下面是一个使用 threading.Condition 的简单示例 import threadingcar_condition threading.Condition() toll_collector_semaphore threading.Semaphore(value0)def waiting_for_release(name: str):print(f{name} 到达等待放行)# 记录当前有等待放行toll_collector_semaphore.release()with car_condition:car_condition.wait()print(f{name} 放行)def toll_collector():while True:toll_collector_semaphore.acquire()with car_condition:# 放行一辆car_condition.notify()cars [A, B, C, D]# 启动收费员 threading.Thread(targettoll_collector).start()for car in cars:threading.Thread(targetwaiting_for_release, args(car,)).start()11. 参考 python 实现线程之间的通信Python 多线程编程-07-threading 模块 - Barrier
- 上一篇: 林芝做网站在网站中添加百度地图
- 下一篇: 临安建设工程规划公示网站域名是什么意思怎么查
相关文章
-
林芝做网站在网站中添加百度地图
林芝做网站在网站中添加百度地图
- 技术栈
- 2026年03月21日
-
林业网站建设方案wordpress首页布局插件
林业网站建设方案wordpress首页布局插件
- 技术栈
- 2026年03月21日
-
林业厅网站建设招标深圳设计公司招聘信息
林业厅网站建设招标深圳设计公司招聘信息
- 技术栈
- 2026年03月21日
-
临安建设工程规划公示网站域名是什么意思怎么查
临安建设工程规划公示网站域名是什么意思怎么查
- 技术栈
- 2026年03月21日
-
临安区建设局网站陕西省建设工程招投标信息网官网
临安区建设局网站陕西省建设工程招投标信息网官网
- 技术栈
- 2026年03月21日
-
临安市建设局门户网站网页制作怎么添加视频
临安市建设局门户网站网页制作怎么添加视频
- 技术栈
- 2026年03月21日
