python 多线程之信号机Semaphore、事件Event
2012-09-03 10:50
585 查看
信号机semaphore
是一个变量,控制着对公共资源或者临界区的访问。信号机维护着一个计数器,指定可同时访问资源或者进入临界区的线程数。每次有一个线程获得信号机时,计数器-1。若计数器为0,其他线程就停止访问信号机,直到另一个线程释放信号机。
SemaphoreThread类的每个对象代表饭馆里的一个客人。类属性availableTables跟踪饭馆中可用的桌子。
信号机有个内建的计数器,用于跟踪他的acquire和release方法调用的次数。内部计数器的初始值可作为参数传给Semaphore构造函数。默认值为1.计数器大于0,Semaphore的acquire方法就为线程获得信号机,并计数器自减。
事件
threading模块定义了可用于线程通讯的Event(事件)类。Event有一个内部标识,可为True或者False,一个或多个线程能调用Event对象的wait方法以暂停并等待事件发生。
是一个变量,控制着对公共资源或者临界区的访问。信号机维护着一个计数器,指定可同时访问资源或者进入临界区的线程数。每次有一个线程获得信号机时,计数器-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方法以暂停并等待事件发生。
相关文章推荐
- 详解python多线程、锁、event事件机制的简单使用
- Python基础之多线程事件Event
- python多线程之事件Event的使用详解
- python笔记12-python多线程之事件(Event)
- python多线程之Event(事件)
- 秒杀多线程第六篇 经典线程同步 事件Event
- 秒杀多线程第六篇 经典线程同步 事件Event .
- 秒杀多线程第六篇---经典线程同步 事件Event
- 多线程之六 经典线程同步 事件Event
- day11_python多线程之event代码
- Python Signal(信号) 异步系统事件
- Python Signal(信号) 异步系统事件
- python event多线程回调
- Python pyQt4/PyQt5 学习笔记4(事件和信号)
- 秒杀多线程第六篇 经典线程同步 事件Event
- Python Tulip ( asyncio) 第2节 Base Event Loop 基本事件循环(2) 译文
- 多线程--同步(事件Event)
- python多线程,event,互斥锁,死锁,递归锁,信号量
- 【深度好文】多线程之WaitHandle-->派生EventWaitHandle事件构造-》AutoResetEvent、ManualResetEvent
- python多线程threading事件对象event实现线程阻塞及timer时间对象