Python3中利用BoundedSemaphore限制线程并发数的实现

方予
方予
发布时间:2026-10-13| 3人浏览过
原创

本文介绍Python3中如何使用BoundedSemaphore限制线程并发数量。通过示例代码展示如何初始化信号量并配合with语句在爬虫场景中控制同时活动的线程数,确保资源不被过度占用。

前言

近期在深入研习Python的过程中,我意识到掌握线程信号量的基础概念对于透彻理解Python多线程机制至关重要。为了帮助读者更好地应用这一知识,本文将详细讲解在Python3.X环境下如何使用信号量,并通过具体案例进行说明。

方法示例

在线程编程中,信号量的核心作用在于管理有限资源,确保在同一时刻只有指定数量的线程能够访问该资源,从而避免资源竞争或过载。

# -*- coding:utf-8 -*-
""" Created by FizLin on 2017/07/23/-下午10:59
 mail: https://github.com/Fiz1994
 信号量

 maxconnections = 5
...
pool_sema = BoundedSemaphore(value=maxconnections)
Once spawned, worker threads call the semaphore's acquire and release methods when they need to connect to the server:

pool_sema.acquire()
conn = connectdb()
... use connection ...
conn.close()
pool_sema.release()


"""
import threading
import time
import random

sites = ["https://www.baidu.com/", "https://github.com/Fiz1994", "https://stackoverflow.com/",
   "https://www.sogou.com/",
   "http://english.sogou.com/?b_o_e=1&ie=utf8&fr=common_index_nav&query="] * 20
sites_index = 0
maxconnections = 2
pool_sema = threading.BoundedSemaphore(value=maxconnections)


def test():
 with pool_sema:
  global sites_index, sites
  url = str(sites[sites_index])
  k = random.randint(10, 20)
  print("爬去: " + url + " 需要时间 : " + str(k))
  sites_index += 1
  # print(url)
  time.sleep(k)
  print('退出 ', url)


for i in range(100):
 threading.Thread(target=test).start()

通过观察上述程序运行结果可以发现,无论启动多少线程,始终只有2个爬虫任务处于活跃执行状态,这体现了信号量对并发数的有效控制。

总结

以上就是本文关于Python3线程信号量使用方法的完整介绍。希望这些内容能为您的学习或工作提供有价值的参考。如果您在阅读过程中有任何疑问或想法,欢迎在下方留言交流,感谢大家对本站的支持。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。