[转载] Python3.X 线程中信号量的使用方法示例
參考鏈接: 示例說明Python2.x和Python3.x之間的重要區(qū)別
信號(hào)量semaphore 是一個(gè)變量,控制著對(duì)公共資源或者臨界區(qū)的訪問。信號(hào)量維護(hù)著一個(gè)計(jì)數(shù)器,指定可同時(shí)訪問資源或者進(jìn)入臨界區(qū)的線程數(shù)。下面這篇文章主要給大家介紹了關(guān)于Python3.X 線程中信號(hào)量的使用方法,需要的朋友可以參考借鑒,下面來一起看看吧。 前言?
最近在學(xué)習(xí)python,發(fā)現(xiàn)了解線程信號(hào)量的基礎(chǔ)知識(shí),對(duì)深入理解python的線程會(huì)大有幫助。所以本文將給大家介紹Python3.X線程中信號(hào)量的使用方法,下面話不多說,來一起看看詳細(xì)的介紹:?
方法示例?
線程中,信號(hào)量主要是用來維持有限的資源,使得在一定時(shí)間使用該資源的線程只有指定的數(shù)量?
# -*- coding:utf-8 -*-
""" Created by FizLin on 2017/07/23/-下午10:59
?mail: https://github.com/Fiz1994
?信號(hào)量
?
?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 + " 需要時(shí)間 : " + 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個(gè)爬蟲是處于活動(dòng)狀態(tài) 推薦我們的python學(xué)習(xí)基地,看老程序是如何學(xué)習(xí)的!從基礎(chǔ)的python腳本、爬蟲、django、數(shù)據(jù)挖掘等編程技術(shù),工作經(jīng)驗(yàn),還有前輩精心為學(xué)習(xí)python的小伙伴整理零基礎(chǔ)到項(xiàng)目實(shí)戰(zhàn)的資料,!每天都有程序員定時(shí)講解Python技術(shù),分享一些學(xué)習(xí)的方法和需要留意的小細(xì)節(jié) 總結(jié)?
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來一定的幫助
總結(jié)
以上是生活随笔為你收集整理的[转载] Python3.X 线程中信号量的使用方法示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: aio nio aio_AIO的完整形式
- 下一篇: [转载] python数组的使用