• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

关于Python3.X线程中信号量的使用详解

python 搞代码 4年前 (2022-01-09) 15次浏览 已收录 0个评论

信号量semaphore 是一个变量,控制着对公共资源或者临界区的访问。信号量维护着一个计数器,指定可同时访问资源或者进入临界区的线程数。下面这篇文章主要给大家介绍了关于Python3.X 线程中信号量的使用方法,需要的朋友可以参考借鉴,下面来一起看看吧。

前言

最近在学习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 threadingimport timeimport randomsites = ["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="] * 20sites_index = 0maxconnections = 2pool_sema = threading.BoundedSemaphore(value=maxconnections)def test(): with pool_sema:  global sites_index, sites  url = str(sites[sites_index])  k = r<div>本文来源gaodai.ma#com搞##代!^码7网</div>andom.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.X线程中信号量的使用详解的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:关于Python3.X线程中信号量的使用详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址