Python3.X线程中信号量的使用 Python3.X 线程中信号量如何使用示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python3.X线程中信号量的使用 Python3.X 线程中信号量如何使用示例

FIZLIN   2021-03-24 我要评论
想了解Python3.X 线程中信号量怎样使用示例的相关内容吗,FIZLIN在本文为您仔细讲解Python3.X线程中信号量的使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:python,多线程,信号量,python,线程信号量,python,线程,使用,下面大家一起来学习吧。

前言

最近在学习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个爬虫是处于活动状态

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对的支持。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们