1. 程式人生 > >11.python並發入門(part6 Semaphore信號量)

11.python並發入門(part6 Semaphore信號量)

semaphore python 信號量

一、什麽是信號量。

信號量也是一種鎖。

信號量的主要用途是用來控制線程的並發量的,BoundedSemaphore或Semaphore管理一個內置的計數器,每調用一次acquire()方法時,計數器-1,每調用一次release()方法時,內部計數器+1。

不過需要註意的是,Semaphore內部的計數器不能小於0!當它內部的計數器等於0的時候,這個線程會被鎖定,進入阻塞狀態,直到其他線程去調用release方法。

BoundedSemaphore與Semaphore的唯一區別在於前者將在調用release()時檢查計數 器的值是否超過了計數器的初始值,如果超過了將拋出一個異常。


二、信號量使用的示例。

#!/usr/local/bin/python2.7

# -*- coding:utf-8 -*-

import threading

import time

semaphore = threading.Semaphore(5) #設置同一次只能最多有5個線程通過。

def func():

if semaphore.acquire():

print threading.currentThread().getName() + "semaphore"

time.sleep(2)

semaphore.release()

for _ in range(20):

t1 = threading.Thread(target=func)

t1.start()


輸出運行結果:

Thread-1semaphore

Thread-2semaphore

Thread-3semaphore

Thread-4semaphore

Thread-5semaphore


Thread-6semaphore

Thread-7semaphore

Thread-8semaphore

Thread-9semaphore

Thread-10semaphore


Thread-13semaphore

Thread-11semaphore

Thread-12semaphore

Thread-14semaphore

Thread-15semaphore


Thread-17semaphore

Thread-20semaphore

Thread-19semaphore

Thread-18semaphore

Thread-16semaphore


一次最多放行了5個線程,這個和停車位的概念有點像。


三、信號量與遞歸鎖的區別。

個人理解~信號量和遞歸鎖的差別是不是,在信號量中,同一把鎖,多個線程可以操作同一個共享數據,在遞歸鎖在鎖被釋放之前一個線程只能操作一個共享數據。



本文出自 “reBiRTH” 博客,請務必保留此出處http://suhaozhi.blog.51cto.com/7272298/1925456

11.python並發入門(part6 Semaphore信號量)