Python3.X 線程中信號量的使用方法示例
前言
最近在學(xué)習(xí)python,發(fā)現(xiàn)了解線程信號量的基礎(chǔ)知識,對深入理解python的線程會大有幫助。所以本文將給大家介紹Python3.X線程中信號量的使用方法,下面話不多說,來一起看看詳細(xì)的介紹:
方法示例
線程中,信號量主要是用來維持有限的資源,使得在一定時間使用該資源的線程只有指定的數(shù)量
# -*- 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()
可以發(fā)現(xiàn)該程序中,永遠(yuǎn)只有2個爬蟲是處于活動狀態(tài)

總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Python網(wǎng)絡(luò)爬蟲與信息提取(實例講解)
下面小編就為大家?guī)硪黄狿ython網(wǎng)絡(luò)爬蟲與信息提取(實例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
python3翻轉(zhuǎn)字符串里的單詞點的實現(xiàn)方法
這篇文章主要介紹了python3翻轉(zhuǎn)字符串里的單詞點的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
Python 抓取數(shù)據(jù)存儲到Redis中的操作
這篇文章主要介紹了Python 抓取數(shù)據(jù)存儲到Redis中的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
詳解Python如何利用Pandas與NumPy進(jìn)行數(shù)據(jù)清洗
許多數(shù)據(jù)科學(xué)家認(rèn)為獲取和清理數(shù)據(jù)的初始步驟占工作的 80%,花費(fèi)大量時間來清理數(shù)據(jù)集并將它們歸結(jié)為可以使用的形式。本文將利用 Python 的 Pandas和 NumPy 庫來清理數(shù)據(jù),需要的可以參考一下2022-04-04

