# -*- coding:utf-8 -*-
""" Created by FizLin on 2017/07/23/-下午10:59
mail: https://github测试数据/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://HdhCmsTestbaidu测试数据/", "https://github测试数据/Fiz1994", "https://stackoverflow测试数据/",
"https://HdhCmsTestsogou测试数据/",
"http://english.sogou测试数据/?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.X线程中信号量的使用详解的详细内容,更多请关注Gxl网其它相关文章!
查看更多关于关于Python3.X线程中信号量的使用详解的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did81833