您的位置:首页 > 编程语言 > Python开发

python 多线程之信号机Semaphore、事件Event

2012-09-03 10:50 585 查看
信号机semaphore

是一个变量,控制着对公共资源或者临界区的访问。信号机维护着一个计数器,指定可同时访问资源或者进入临界区的线程数。每次有一个线程获得信号机时,计数器-1。若计数器为0,其他线程就停止访问信号机,直到另一个线程释放信号机。

import threading
import random
import time

class SemaphoreThread(threading.Thread):
"""classusing semaphore"""

availableTables=['A','B','C','D','E']

def__init__(self,threadName,semaphore):
"""initialize thread"""

threading.Thread.__init__(self,name=threadName)
self.sleepTime=random.randrange(1,6)
#set the semaphore as a data attribute of the class
self.threadSemaphore=semaphore
defrun(self):
"""Print message and release semaphore"""

#acquire the semaphore
self.threadSemaphore.acquire()
#remove a table from the list
table=SemaphoreThread.availableTables.pop()
print "%s entered;seated at table %s." %(self.getName(),table),
print SemaphoreThread.availableTables
time.sleep(self.sleepTime)
#free a table
print " %s exiting;freeing table %s." %(self.getName(),table),
SemaphoreThread.availableTables.append(table)
print SemaphoreThread.availableTables
#release the semaphore after execution finishes
self.threadSemaphore.release()

threads=[] #list of threads
#semaphore allows five threads to enter critical section
threadSemaphore=threading.Semaphore(len(SemaphoreThread.availableTables))
#创建一个threading.Semaphore对象,他最多允许5个线程访问临界区。
#Semaphore类的一个对象用计数器跟踪获取和释放信号机的线程数量。
#create ten threads
for i in range(1,11):
threads.append(SemaphoreThread("thread"+str(i),threadSemaphore))
#创建一个列表,该列表由SemaphoreThread对象构成,start方法开始列表中的每个线程
#start each thread
for thread in threads:
thread.start()


SemaphoreThread类的每个对象代表饭馆里的一个客人。类属性availableTables跟踪饭馆中可用的桌子。

信号机有个内建的计数器,用于跟踪他的acquire和release方法调用的次数。内部计数器的初始值可作为参数传给Semaphore构造函数。默认值为1.计数器大于0,Semaphore的acquire方法就为线程获得信号机,并计数器自减。

事件

threading模块定义了可用于线程通讯的Event(事件)类。Event有一个内部标识,可为True或者False,一个或多个线程能调用Event对象的wait方法以暂停并等待事件发生。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: