国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python3.X 線程中信號量的使用方法示例

2020-02-16 01:57:00
字體:
來源:轉載
供稿:網友

前言

最近在學習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 threadingimport timeimport randomsites = ["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="] * 20sites_index = 0maxconnections = 2pool_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個爬蟲是處于活動狀態

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對武林站長站的支持。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 大理市| 万州区| 富民县| 来安县| 常德市| 遂溪县| 突泉县| 越西县| 永修县| 石景山区| 双城市| 华池县| 奉新县| 丹江口市| 鹤岗市| 哈尔滨市| 周至县| 广宗县| 义乌市| 兴隆县| 长海县| 高安市| 阿城市| 宁明县| 浏阳市| 托克托县| 饶阳县| 万年县| 桐梓县| 九江县| 泽州县| 宁乡县| 云南省| 梧州市| 本溪| 肥西县| 武安市| 定边县| 岳阳市| 鄂伦春自治旗| 鹤岗市|