python学习笔记三---segmaphore信号量学习
2014-06-22 21:48
190 查看
# *-* coding=gb2312 *-* ''' 信号量semaphore 是一个变量,控制着对公共资源或者临界区的访问。信号量维护着一个计数器,指定可同时访问资源或者进入临界区的线程数。 每次有一个线程获得信号量时,计数器-1。若计数器为0,其他线程就停止访问信号量,直到另一个线程释放信号量。 ''' import threading import random import time class MyThread(threading.Thread): availableTables=['A','B','C','D','E'] def __init__(self,threadName,semaphore): self.interval =random.randrange(1,6) self.semaphore =semaphore threading.Thread.__init__(self,name=threadName) def run(self): self.semaphore.acquire() #acquire a semaphore table = MyThread.availableTables.pop() print "%s entered;seated at table %s." %(self.getName(),table) time.sleep(self.interval) #free a table print "%s exiting,freeing table %s." %(self.getName(),table) MyThread.availableTables.append(table) self.semaphore.release() mySemaphore = threading.Semaphore(len(MyThread.availableTables)) def Test(): threads=[] for i in range(1,10): threads.append(MyThread("thread"+str(i),mySemaphore)) for i in range(len(threads)): threads[i].start() if __name__ == '__main__': Test()
相关文章推荐
- Python学习笔记14:标准库之信号量(signal包)
- Python学习笔记:Python Language Features
- Boost.Python学习笔记
- Python 学习笔记 - 2.自省
- python文件读写实例学习笔记
- Python学习笔记1
- python(异常处理机制,学习笔记摘要)
- python学习笔记(1)
- Python 学习笔记(1)
- Python 学习笔记 (转载)
- Python学习笔记
- if __name__ (python学习笔记一,注意前面是双下划线)
- python学习笔记(二)
- python学习笔记(2)
- python学习笔记1
- Python学习笔记(一)
- [原创]Ruby学习笔记(4)-闰年、季节和月份天数的Ruby版和Python版
- Python学习笔记 Module
- Python 正则式学习笔记
- python学习笔记,整形,字符串