python信号量怎么用_Python3.X 线程中信号量的使用方法示例

本文介绍如何使用Python的`threading`模块和`BoundedSemaphore`来限制并发连接数,确保爬虫在`maxconnections=5`时不会过度占用资源。通过实例展示了如何在100个线程中,每个线程获取和释放信号量进行数据库连接操作。
摘要由CSDN通过智能技术生成

# -*- 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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值