【Rollo的Python之路】Python 信号量 学习笔记 Semaphore

Python 信号量 学习笔记 Semaphore

信号量semaphore 是用于控制进入数量的锁。有哪些应用场景呢,比如说在读写文件的时候,一般只能只有一个线程在写,而读可以有多个线程同时进行,如果需要限制同时读文件的线程个数,这时候就可以用到信号量了(如果用互斥锁,就是限制同一时刻只能有一个线程读取文件)。又比如在做爬虫的时候,有时候爬取速度太快了,会导致被网站禁止,所以这个时候就需要控制爬虫爬取网站的频率。
 
一般用BounderSemaphore
实例:
 
import threading,time

class myThread(threading.Thread):
    def run(self):
        if semaphore.acquire():
            print(self.name)
            time.sleep(5)
            semaphore.release()

if __name__ == "__main__":
    semaphore = threading.BoundedSemaphore(5)
    thrs = []
    for i in range(100):
        thrs.append(myThread())

    for t in thrs:

        t.start()

 

posted @ 2019-05-29 22:42  Rollo|St  阅读(261)  评论(0编辑  收藏  举报