關於Python3.X線程中信號量的使用詳解

黄舟
發布: 2017-07-24 15:20:21
原創
1708 人瀏覽過

信號量semaphore 是一個變量,控制著對公共資源或臨界區的存取。信號量維護一個計數器,指定可同時存取資源或進入臨界區的執行緒數。以下這篇文章主要為大家介紹了關於Python3.X 線程中信號量的使用方法,需要的朋友可以參考借鑒,下面來一起看看吧。

前言

最近在學習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個爬蟲是處於活動狀態

總結

########

以上是關於Python3.X線程中信號量的使用詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!